我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
谢谢你的回答!
我还稍微调整了它,使它更像数组。拼接方法(并考虑了@Ates的笔记):
spliceString=function(string, index, numToDelete, char) {
return string.substr(0, index) + char + string.substr(index+numToDelete);
}
var myString="hello world!";
spliceString(myString,myString.lastIndexOf('l'),2,'mhole'); // "hello wormhole!"
其他回答
我做了一个类似于你问的函数,它检查字符串中的字符是否在不允许字符数组中如果是它就用"
var validate = function(value){
var notAllowed = [";","_",">","<","'","%","$","&","/","|",":","=","*"];
for(var i=0; i<value.length; i++){
if(notAllowed.indexOf(value.charAt(i)) > -1){
value = value.replace(value.charAt(i), "");
value = validate(value);
}
}
return value;
}
假设你想用“Z”替换第k个索引(基于0的索引)。 你可以用正则表达式来做这个。
var re = var re = new RegExp("((.){" + K + "})((.){1})")
str.replace(re, "$1A$`");
你不能。取位置前后的字符并连接成一个新字符串:
var s = "Hello world";
var index = 3;
s = s.substring(0, index) + 'x' + s.substring(index + 1);
var str = “hello world”; console.log(str); var arr = [...p]; arr[0] = “H”; p = arr.join(“”); console.log(str);
下面是我使用三元和映射操作符的解决方案。如果你问我,我觉得可读性更强,更易维护,更容易理解。
它更注重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()”/>