0

I have a string like this

'I am a beautiful string ABC where sometimes ABC there ABC are weird tokens ABC'

I need to insert another token, let's say '123', before any occurrence of the token 'ABC' in my string. In other words the result I want to obtain is

'I am a beautiful string 123ABC where sometimes 123ABC there 123ABC are weird tokens 123ABC'

I have tried several solutions, but none looks to me elegant. Any suggestion to solve this problem would be appreciated.

Picci
  • 16,775
  • 13
  • 70
  • 113

2 Answers2

1

You can use split and join

console.log(
  'I am a beautiful string ABC where sometimes ABC there ABC are weird tokens ABC'
  .split("ABC")
  .join("123ABC")
)  
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

You could replace the string by searching for ABC and add a prefix '123' to the found substring.

var string = 'I am a beautiful string ABC where sometimes ABC there ABC are weird tokens ABC',
    result = string.replace(/ABC/g, '123$&');

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392