我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
var str = “hello world”; console.log(str); var arr = [...p]; arr[0] = “H”; p = arr.join(“”); console.log(str);
其他回答
这里的方法很复杂。 我会这样做:
var myString = "this is my string";
myString = myString.replace(myString.charAt(number goes here), "insert replacement here");
这很简单。
您可以使用子字符串函数在目标索引之前和目标索引之后首先选择文本,然后与您潜在的字符或字符串进行连接。这个更好
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);
使用字符串的一行程序。替换回调(不支持表情符号):
// 0 - index to replace, 'f' - replacement string
'dog'.replace(/./g, (c, i) => i == 0? 'f': c)
// "fog"
解释道:
//String.replace will call the callback on each pattern match
//in this case - each character
'dog'.replace(/./g, function (character, index) {
if (index == 0) //we want to replace the first character
return 'f'
return character //leaving other characters the same
})
可以使用以下函数替换字符串特定位置的字符或字符串。使用String.prototype.replaceAllMatches()函数替换以下所有匹配案例。
String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
var retStr = this, repeatedIndex = 0;
for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
if (repeatedIndex == 0 && x == 0) {
repeatedIndex = retStr.indexOf(matchkey);
} else { // matchIndex > 0
repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
}
if (x == matchIndex) {
retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
matchkey = null; // To break the loop.
}
}
return retStr;
};
测试:
var str = "yash yas $dfdas.**";
console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );
输出:
Index Matched replace : yash yas $dfd*.**
Index Matched replace : yash ~as $dfdas.**
如果你想替换字符串中的字符,你应该创建可变字符串。这些本质上是字符数组。你可以创建一个工厂:
function MutableString(str) {
var result = str.split("");
result.toString = function() {
return this.join("");
}
return result;
}
然后你可以访问字符,整个数组转换为字符串时使用的字符串:
var x = MutableString("Hello");
x[0] = "B"; // yes, we can alter the character
x.push("!"); // good performance: no new string is created
var y = "Hi, "+x; // converted to string: "Hi, Bello!"