admin 管理员组

文章数量: 1184232

I like to replace a string after a specific index.

ex:

var str = "abcedfabcdef"
    str.replace ("a","z",2)
    console.log(str) 
    abcedfzbcdef

Is there any way to do this in javascript or in nodeJS?

I like to replace a string after a specific index.

ex:

var str = "abcedfabcdef"
    str.replace ("a","z",2)
    console.log(str) 
    abcedfzbcdef

Is there any way to do this in javascript or in nodeJS?

Share Improve this question edited Sep 1, 2017 at 23:49 Shankar asked Sep 1, 2017 at 23:45 ShankarShankar 1432 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

There is no direct way using the builtin replace function but you can always create a new function for that:

String.prototype.betterReplace = function(search, replace, from) {
  if (this.length > from) {
    return this.slice(0, from) + this.slice(from).replace(search, replace);
  }
  return this;
}

var str = "abcedfabcdef"
console.log(str.betterReplace("a","z","2"))

Regular expression alternative, but replaces all occurrences after specific index:

console.log( 'abcabcabc'.replace(/a/g, (s, i) => i > 2 ? 'z' : s) )

本文标签:

Error[2]: Invalid argument supplied for foreach(), File: /www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm, Line: 58
File: /www/wwwroot/roclinux.cn/tmp/route_read.php, Line: 205, include(/www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm)
File: /www/wwwroot/roclinux.cn/tmp/index.inc.php, Line: 129, include(/www/wwwroot/roclinux.cn/tmp/route_read.php)
File: /www/wwwroot/roclinux.cn/index.php, Line: 29, include(/www/wwwroot/roclinux.cn/tmp/index.inc.php)