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
  • 14,956
  • 9
  • 61
  • 98

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
  • 155,085
  • 27
  • 166
  • 222
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
  • 351,820
  • 24
  • 303
  • 358