我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
下面是我想出的一个版本,如果你想在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;
}
其他回答
概括Afanasii Kurakin的回答,我们有:
函数替换(str, index, ch) { 返回str.replace(/。/g, (c, i) => i == index ?Ch: c); } let str = 'Hello World'; str = replacat (str, 1, 'u'); console.log (str);// hello World
让我们展开并解释正则表达式和replace函数:
函数replace (str, index, newChar) { 函数替换符(origChar, strIndex) { if (strIndex === index) 返回newChar; 其他的 返回origChar; } 返回str.replace(/。/ g,替代者); } let str = 'Hello World'; str = replacat (str, 1, 'u'); console.log (str);// hello World
正则表达式。恰好匹配一个字符。g使它匹配for循环中的每个字符。给定原始字符和该字符在字符串中位置的下标,将调用replacement函数。我们用一个简单的if语句来决定返回的是origChar还是newChar。
这很容易用RegExp实现!
const str = 'Hello RegEx!';
const index = 11;
const replaceWith = 'p';
//'Hello RegEx!'.replace(/^(.{11})(.)/, `$1p`);
str.replace(new RegExp(`^(.{${ index }})(.)`), `$1${ replaceWith }`);
//< "Hello RegExp"
使用字符串的一行程序。替换回调(不支持表情符号):
// 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
})
你可以试试
var strArr = str.split("");
strArr[0] = 'h';
str = strArr.join("");
假设你想用“Z”替换第k个索引(基于0的索引)。 你可以用正则表达式来做这个。
var re = var re = new RegExp("((.){" + K + "})((.){1})")
str.replace(re, "$1A$`");