Superman
Superman

Reputation: 21

How to replace a string in a string with a given array

I get a array which is like:

const u = ['JS', 'rock']

And I get a string which is like:

const s = 'I like JS, and rock'

Here is my work:

u.map(e => s.replaceAll(e,'hi'))

And here is the expected result:

I like hi, and hi

But here is the result I get:

I like JS, and rock

How can I correct it?

Upvotes: 0

Views: 88

Answers (3)

HoM
HoM

Reputation: 131

s.replaceAll returning a value but not edit s . so you can use this code:

let s = 'I like JS, and rock'
const u = ['JS', 'rock']
u.map(e =>{ s=s.replaceAll(e,'hi')})

Upvotes: 0

D. Seah
D. Seah

Reputation: 4592

 const s = 'I like JS, and rock'
 const u = ['JS', 'rock']

 console.log(u.reduce((a, c) => a.replaceAll(c,'hi'), s));

you can use reduce instead of map

Upvotes: 2

Nick
Nick

Reputation: 16576

If you join your search terms with a pipe (|), you can actually do this with one regular expression (generally faster than mapping in JS). You can pass 'g' as the second argument to the RegExp constructor to make sure it's a global search on the string.

const u = ['JS', 'rock']

const s = 'I like JS, and rock'

const regex = new RegExp(u.join('|'), 'g');

console.log(
  s.replace(regex, 'hi')
)

Upvotes: 0

Related Questions