admin管理员组文章数量:1289868
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 badges2 Answers
Reset to default 7There 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) )
本文标签:
版权声明:本文标题:node.js - replace a string after specific index in javascript str.replace(from, to, indexfrom) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741402630a2376760.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论