aikich aikich - 1 year ago 35
Javascript Question

Javascript replace substring doesn't work well if the string repeats

I have a quite simple problem with substring/substr/slice. My code is very complicated so I won't post it here, but here is the simplified version of the problem:

For example how to change text.substring(5, 10) to "Something"?

text = "HelloHello";

if I try

text = text.replace(text.substring(5,10), "Something");

the result will be "SomethingHello", because text.substring(0, 5) was also "Hello", but I want to get "HelloSomething"

It doesn't work with slice() and substr() either, can you show me a solution?

Answer Source

Based on comments below, I have wrote next function:

text = "HelloHello"

// This function replace all of the text to word between the two index (start, end)
function replace(start, end, text, word) {
  result = text.substring(0, start) + word + text.substring(end, text.length)

  return result

text = replace(5, 10, text, "Something")

console.log(text) // "HelloSomething"