Search code examples
javascriptreplacesubstringslicesubstr

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?


Solution

  • Based on comments below, I have wrote function replacePartOfText().

    This function replace all of the text to word between the two index (start, end)

    text = "HelloHello"
    
    function replacePartOfText(text, start, end, word) {
      result = text.substring(0, start) + word + text.substring(end, text.length)
    
      return result
    }
    
    text = replacePartOfText(text, 5, 10, "Something")
    
    console.log(text) // "HelloSomething"