我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
这类似于Array.splice:
String.prototype.splice = function (i, j, str) {
return this.substr(0, i) + str + this.substr(j, this.length);
};
其他回答
JavaScript中没有replacat函数。你可以使用下面的代码替换任意字符串中指定位置的任意字符:
函数 rep() { var str = 'Hello World'; str = setCharAt(str,4,'a'); 警报; } 函数集CharAt(str,index,chr) { if(索引 > str.length-1) 返回 str; 返回 str.substring(0,index) + chr + str.substring(index+1); } <button onclick=“rep();”>click</button>
下面是我想出的一个版本,如果你想在react/javascript的索引中设置单词或单个字符的样式。
replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings )
工作示例:https://codesandbox.io/s/ov7zxp9mjq
function replaceAt(indexArray, [...string]) {
const replaceValue = i => string[i] = <b>{string[i]}</b>;
indexArray.forEach(replaceValue);
return string;
}
这是另一种方法
function replaceAt(indexArray, [...string]) {
const startTag = '<b>';
const endTag = '</b>';
const tagLetter = i => string.splice(i, 1, startTag + string[i] + endTag);
indexArray.forEach(tagLetter);
return string.join('');
}
和另一个……
function replaceAt(indexArray, [...string]) {
for (let i = 0; i < indexArray.length; i++) {
string = Object.assign(string, {
[indexArray[i]]: <b>{string[indexArray[i]]}</b>
});
}
return string;
}
您可以使用子字符串函数在目标索引之前和目标索引之后首先选择文本,然后与您潜在的字符或字符串进行连接。这个更好
const myString = "Hello world";
const index = 3;
const stringBeforeIndex = myString.substring(0, index);
const stringAfterIndex = myString.substring(index + 1);
const replaceChar = "X";
myString = stringBeforeIndex + replaceChar + stringAfterIndex;
console.log("New string - ", myString)
or
const myString = "Hello world";
let index = 3;
myString = myString.substring(0, index) + "X" + myString.substring(index + 1);
"hello world".replace(/(.{3})./, "$1h")
// 'helho world'
var str = “hello world”; console.log(str); var arr = [...p]; arr[0] = “H”; p = arr.join(“”); console.log(str);