JavaScript中如何替换字符串的指定索引位置的字符?
黄太龙
JavaScript并不提供这样的内置方法来实现替换字符串指定索引位置的字符,但是可以自定义这样的方法,如下所示:
String.prototype.replaceByIndex=function(index, newString) { return this.substr(0, index) + newString + this.substr(index + newString.length); }
如下使用即可,这种替换字符串指定索引位置的替换方式是从指定索引位置开始替换,会对指定索引位置之后的字符有影响:
>>> s = "01234567" "01234567" >>> s.replaceByIndex( 1, "a" ) "0a234567" >>> s.replaceByIndex( 1, "abc" ) "0abc4567"
【更加推荐这种方式】如果是想把js中指定索引位置的某个字符替换成某个字符串,那如下自定义:
String.prototype.replaceByIndex=function(index, newString) { return this.substr(0, index) + newString + this.substr(index + 1 ); }
运行结果如下:
>>> s = "01234567" "01234567" >>> s.replaceByIndex( 1, "abc" ) "0abc234567"
实际使用中不管是用哪种自定义替换指定索引位置的字符,使用内置方法,字符串本体不会改变,如有需要需把替换的结果赋值给原来的字符串变量:
>>> s = "01234567" "01234567" >>> s.replaceByIndex( 1, "abc" ) "0abc234567" >>> s "01234567" >>> s = s.replaceByIndex( 1, "abc" ) "0abc234567" >>> s "0abc234567"