我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
我用负下标的安全方法
/**
* @param {string} str
* @param {number} index
* @param {string} replacement
* @returns {string}
*/
static replaceAt (str, index, replacement)
{
if (index < 0) index = str.length + index
if (index < 0 || index >= str.length) throw new Error(`Index (${index}) out of bounds "${str}"`)
return str.substring(0, index) + replacement + str.substring(index + 1)
}
像这样使用它:
replaceAt('my string', -1, 'G') // 'my strinG'
replaceAt('my string', 2, 'yy') // 'myyystring'
replaceAt('my string', 22, 'yy') // Uncaught Error: Index (22) out of bounds "my string"
其他回答
这里的方法很复杂。 我会这样做:
var myString = "this is my string";
myString = myString.replace(myString.charAt(number goes here), "insert replacement here");
这很简单。
在JavaScript中,字符串是不可变的,这意味着您所能做的最好的事情就是用更改后的内容创建一个新的字符串,并将变量赋值指向它。
你需要自己定义replace()函数:
String.prototype.replaceAt = function(index, replacement) {
return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}
像这样使用它:
var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // He!!o World
在Javascript中,字符串是不可变的,所以你必须这样做
var x = "Hello world"
x = x.substring(0, i) + 'h' + x.substring(i+1);
用'h'替换x在i处的字符
与vector打交道通常最有效的方法是接触String。
我建议使用以下函数:
String.prototype.replaceAt=function(index, char) {
var a = this.split("");
a[index] = char;
return a.join("");
}
运行这段代码:
String.prototype.replaceAt=function(index, char) { var a = this.split(“”); a[索引] = 字符; 返回 a.join(“”); } var str = “hello world”; str = str.replaceAt(3, “#”); document.write(str);
谢谢你的回答!
我还稍微调整了它,使它更像数组。拼接方法(并考虑了@Ates的笔记):
spliceString=function(string, index, numToDelete, char) {
return string.substr(0, index) + char + string.substr(index+numToDelete);
}
var myString="hello world!";
spliceString(myString,myString.lastIndexOf('l'),2,'mhole'); // "hello wormhole!"