Я хочу заменить текст между двумя индексами в Javascript, что-то вроде:
str = "The Hello World Code!";
str.replaceBetween(4,9,"Hi");
// outputs "The Hi World Code"
Индексы и строка являются динамическими.
Как я могу это сделать?
Я хочу заменить текст между двумя индексами в Javascript, что-то вроде:
str = "The Hello World Code!";
str.replaceBetween(4,9,"Hi");
// outputs "The Hi World Code"
Индексы и строка являются динамическими.
Как я могу это сделать?
В JavaScript нет такого метода. Но вы всегда можете создать свой собственный:
String.prototype.replaceBetween = function(start, end, what) {
return this.substring(0, start) + what + this.substring(end);
};
console.log("The Hello World Code!".replaceBetween(4, 9, "Hi"));
В JavaScript есть метод Array.splice
, который выполняет это задание, но не String.splice
. Однако, если вы преобразовываете строку в массив:
var str = "The Hello World Code!";
var arr = str.split('');
var removed = arr.splice(4,5,"Hi"); // arr is modified
str = arr.join('');
Другой подход, когда вам нужно полностью заменить строку в определенном индексе, с тем же вызовом функции с String.prototype.replace
может быть следующим:
String.prototype.replaceAt = function(index, fromString, toString) {
let hasWrongParams = typeof index !== 'number'
|| !fromString || typeof fromString !== 'string'
|| !toString || typeof toString !== 'string';
if(hasWrongParams) return '';
let fromIndex = index;
let toIndex = index + fromString.length;
return this.substr(0, fromIndex) + toString + this.substr(toIndex);
}
https://gist.github.com/kwnccc/9df8554474e39f4b17a07efbbdf7971c
Например:
let string = 'This is amazing world, it still amazing!';
string.replaceAt(8, 'amazing', 'worderful');
// 'This is worderful world, it still amazing!'
string.replaceAt(34, 'amazing', 'worderful');
// 'This is amazing world, it still worderful!'
Вот как это сработало для меня.
var str = "The Hello World Code!";
var newStr="Hi"
var startIndex= 4; // start index of 'H' from 'Hello'
var endIndex= 8; // end index of 'o' from 'Hello'
var preStr = str.substring(0, startIndex);
var postStr = str.substring(endIndex+1, str.length - 1);
var result = preStr+newStr+postStr;); // outputs "The Hi World Code"
скрипт: http://jsfiddle.net/ujvus6po/1/
Более надежная версия решения VisioN, которая обнаруживает ошибки вне диапазона и RangeError
значимые и простые для отладки RangeError
. Если вы хотите, вы можете также расширить String.prototype
.
function replaceString(str, start, end, replace) {
if (start < 0 || start > str.length) {
throw new RangeError('start index ${start} is out of the range 0~${str.length}');
}
if (end > str.length || end < start) {
throw new RangeError('end index ${end} is out of the range ${start}~${str.length}');
}
return str.substring(0, start) + replace + str.substring(end);
}
// replace in the middle of the string, replacement string can be any length
console.log(replaceString("abcdef", 2, 4, "hhhh")); // output: "abhhhhef"
// insert in the front of the string, start and end index equal to 0
console.log(replaceString("abcdef", 0, 0, "hhhh")); // output: "hhhhabcdef"
// append at the end of the string, start and end index equal to the length of the string
console.log(replaceString("abcdef", 6, 6, "hhhh")); // output: "abcdefhhhh"
// error 1: start index is greater than end index
// console.log(replaceString("abcdef", 4, 2, "hhhh")); // output: RangeError: end index 2 is out of the range 4~6
// error 2: start/end index is less than 0
// console.log(replaceString("abcdef", -2, 2, "hhhh")); // output: RangeError: start index -2 is out of the range 0~6
// error 3: start/end index is greater than length of the string
// console.log(replaceString("abcdef", 3, 20, "hhhh")); // output: RangeError: end index 20 is out of the range 3~6
Принятый ответ правильный, но я хотел избежать расширения строки prototype
:
function replaceBetween(origin, startIndex, endIndex, insertion) {
return origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
}
Использование:
replaceBetween('Hi World', 3, 7, 'People');
// Hi People