我想替换 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"));
接受的答案是正确的,但我想避免扩展 String prototype
:
function replaceBetween(origin, startIndex, endIndex, insertion) {
return origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
}
用法:
replaceBetween('Hi World', 3, 7, 'People');
// Hi People
如果使用简洁的箭头函数,那么它是:
const replaceBetween = (origin, startIndex, endIndex, insertion) =>
origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
如果使用模板文字,那么它是:
const replaceBetween = (origin, startIndex, endIndex, insertion) =>
`${origin.substring(0, startIndex)}${insertion}${origin.substring(endIndex)}`;
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('');
这就是它对我有用的方式。
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/
当您需要使用完全相同的函数调用完全替换特定索引处的字符串时,另一种方法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's still amazing!';
string.replaceAt(8, 'amazing', 'worderful');
// 'This is worderful world, it's still amazing!'
string.replaceAt(34, 'amazing', 'worderful');
// 'This is amazing world, it's still worderful!'
VisioN解决方案的更强大版本,可检测超出范围的错误并抛出有意义且易于调试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