Reputation: 21
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
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
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
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