kql*_*ert 32 javascript jquery
我想在Javascript中的两个索引之间替换文本,例如:
str = "The Hello World Code!";
str.replaceBetween(4,9,"Hi");
// outputs "The Hi World Code"
Run Code Online (Sandbox Code Playgroud)
索引和字符串都是动态的.
我怎么能这样做?
Vis*_*ioN 61
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"));Run Code Online (Sandbox Code Playgroud)
Rob*_*uch 11
接受的答案是正确的,但我想避免扩展 String prototype:
function replaceBetween(origin, startIndex, endIndex, insertion) {
return origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
}
Run Code Online (Sandbox Code Playgroud)
用法:
replaceBetween('Hi World', 3, 7, 'People');
// Hi People
Run Code Online (Sandbox Code Playgroud)
如果使用简洁的箭头函数,那么它是:
const replaceBetween = (origin, startIndex, endIndex, insertion) =>
origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
Run Code Online (Sandbox Code Playgroud)
如果使用模板文字,则为:
const replaceBetween = (origin, startIndex, endIndex, insertion) =>
`${origin.substring(0, startIndex)}${insertion}${origin.substring(endIndex)}`;
Run Code Online (Sandbox Code Playgroud)
Array.spliceJavaScript中有一种方法可以完成这项工作,但是没有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('');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23183 次 |
| 最近记录: |