我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
我做了一个类似于你问的函数,它检查字符串中的字符是否在不允许字符数组中如果是它就用"
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;
}
其他回答
var str = “hello world”; console.log(str); var arr = [...p]; arr[0] = “H”; p = arr.join(“”); console.log(str);
假设你想用“Z”替换第k个索引(基于0的索引)。 你可以用正则表达式来做这个。
var re = var re = new RegExp("((.){" + K + "})((.){1})")
str.replace(re, "$1A$`");
我做了一个类似于你问的函数,它检查字符串中的字符是否在不允许字符数组中如果是它就用"
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;
}
使用字符串的一行程序。替换回调(不支持表情符号):
// 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
})
使用扩展语法,你可以将字符串转换为数组,在给定位置分配字符,然后转换回字符串:
Const STR = "hello world"; 函数replace (s, i, c) { Const arr =[…s];//将字符串转换为数组 Arr [i] = c;//在pos i处设置字符c 返回arr.join(”);//返回字符串 } //打印"hallo world" console.log(replace (str, 1, 'a'));