我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
使用字符串的一行程序。替换回调(不支持表情符号):
// 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
})
其他回答
假设你想用“Z”替换第k个索引(基于0的索引)。 你可以用正则表达式来做这个。
var re = var re = new RegExp("((.){" + K + "})((.){1})")
str.replace(re, "$1A$`");
这里的方法很复杂。 我会这样做:
var myString = "this is my string";
myString = myString.replace(myString.charAt(number goes here), "insert replacement here");
这很简单。
JavaScript中没有replacat函数。你可以使用下面的代码替换任意字符串中指定位置的任意字符:
函数 rep() { var str = 'Hello World'; str = setCharAt(str,4,'a'); 警报; } 函数集CharAt(str,index,chr) { if(索引 > str.length-1) 返回 str; 返回 str.substring(0,index) + chr + str.substring(index+1); } <button onclick=“rep();”>click</button>
我做了一个类似于你问的函数,它检查字符串中的字符是否在不允许字符数组中如果是它就用"
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;
}
您可以使用子字符串函数在目标索引之前和目标索引之后首先选择文本,然后与您潜在的字符或字符串进行连接。这个更好
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);