我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
概括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"
您可以使用子字符串函数在目标索引之前和目标索引之后首先选择文本,然后与您潜在的字符或字符串进行连接。这个更好
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);
在Javascript中,字符串是不可变的,所以你必须这样做
var x = "Hello world"
x = x.substring(0, i) + 'h' + x.substring(i+1);
用'h'替换x在i处的字符
你可以试试
var strArr = str.split("");
strArr[0] = 'h';
str = strArr.join("");
查看打印步骤的函数
steps(3)
// '# '
// '## '
// '###'
function steps(n, i = 0, arr = Array(n).fill(' ').join('')) {
if (i === n) {
return;
}
str = arr.split('');
str[i] = '#';
str = str.join('');
console.log(str);
steps(n, (i = i + 1), str);
}
概括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。