我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
function dothis() { var x = document.getElementById("x").value; var index = document.getElementById("index").value; var text = document.getElementById("text").value; var length = document.getElementById("length").value; var arr = x.split(""); arr.splice(index, length, text); var result = arr.join(""); document.getElementById('output').innerHTML = result; console.log(result); } dothis(); <input id="x" type="text" value="White Dog" placeholder="Enter Text" /> <input id="index" type="number" min="0"value="6" style="width:50px" placeholder="index" /> <input id="length" type="number" min="0"value="1" style="width:50px" placeholder="length" /> <input id="text" type="text" value="F" placeholder="New character" /> <br> <button id="submit" onclick="dothis()">Run</button> <p id="output"></p>
此方法适用于较小长度的字符串,但对于较大的文本可能很慢。
var x = "White Dog";
var arr = x.split(""); // ["W", "h", "i", "t", "e", " ", "D", "o", "g"]
arr.splice(6, 1, 'F');
/*
Here 6 is starting index and 1 is no. of array elements to remove and
final argument 'F' is the new character to be inserted.
*/
var result = arr.join(""); // "White Fog"
其他回答
下面是我使用三元和映射操作符的解决方案。如果你问我,我觉得可读性更强,更易维护,更容易理解。
它更注重es6和最佳实践。
函数替换At() { const replaceAt = document.getElementById('replaceAt').value; const str = 'ThisIsATestStringToReplaceCharAtSomePosition'; const newStr = Array.from(str).map((character, charIndex) => charIndex === (replaceAt - 1) ?'' : 字符).join(''); console.log('New string: ${newStr}'); } <input type=“number” id=“replaceAt” min=“1” max=“44” oninput=“replaceAt()”/>
你可以扩展字符串类型来包含inset方法:
String.prototype.append =函数(索引,值){ 返回this.slice(0,index) + value + this.slice(index); }; var s = "新字符串"; 警报(s。追加(4 "完成"));
然后你可以调用函数:
var str = “hello world”; console.log(str); var arr = [...p]; arr[0] = “H”; p = arr.join(“”); console.log(str);
使用字符串的一行程序。替换回调(不支持表情符号):
// 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
})
"hello world".replace(/(.{3})./, "$1h")
// 'helho world'