我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
在JavaScript中,字符串是不可变的,这意味着您所能做的最好的事情就是用更改后的内容创建一个新的字符串,并将变量赋值指向它。
你需要自己定义replace()函数:
String.prototype.replaceAt = function(index, replacement) {
return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}
像这样使用它:
var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // He!!o World
其他回答
我做了一个类似于你问的函数,它检查字符串中的字符是否在不允许字符数组中如果是它就用"
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 strArr = str.split("");
strArr[0] = 'h';
str = strArr.join("");
这类似于Array.splice:
String.prototype.splice = function (i, j, str) {
return this.substr(0, i) + str + this.substr(j, this.length);
};
我用负下标的安全方法
/**
* @param {string} str
* @param {number} index
* @param {string} replacement
* @returns {string}
*/
static replaceAt (str, index, replacement)
{
if (index < 0) index = str.length + index
if (index < 0 || index >= str.length) throw new Error(`Index (${index}) out of bounds "${str}"`)
return str.substring(0, index) + replacement + str.substring(index + 1)
}
像这样使用它:
replaceAt('my string', -1, 'G') // 'my strinG'
replaceAt('my string', 2, 'yy') // 'myyystring'
replaceAt('my string', 22, 'yy') // Uncaught Error: Index (22) out of bounds "my string"
谢谢你的回答!
我还稍微调整了它,使它更像数组。拼接方法(并考虑了@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!"