skip to Main Content

In JS, I am trying to manipulate a long plain string. I want to add new chars to each match inside the string in order to make a new string. I mean there are multiple values of the searched substring inside the long string. Any ideas?

2

Answers


  1. Use replaceAll

    const s = 'the thesaurus is the best theatrical'
    
    console.log(s.replaceAll('the', 'thexxx'))
    Login or Signup to reply.
  2. If you want to append to certain text fragments, regardless of whether they are in lower or upper case you would need to use a regular expression with the flags g and i and use the group braces (( and )) to represent each encountered occurrence:

    const s = 'Any you can do I can do better. I can do any better than you! 😉'
    
    console.log(s.replace(/(any)/gi, '$1thing'))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search