0

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?

3
  • Your code works too, you forgot to re-assign the output of s.replaceAll(...) back to s. replaceAll does not replace the string in place, but rather gets you a new one. Commented Dec 27, 2020 at 1:13
  • @Akxe I'm finding it returns an array of two strings, neither of them being what the poster wanted. Commented Dec 27, 2020 at 1:20
  • @Noah The map function does, but the replaceAll function on its own, does only return modified string... Commented Dec 27, 2020 at 20:55

3 Answers 3

2
 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

Sign up to request clarification or add additional context in comments.

Comments

0

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')
)

1 Comment

No problem! If you have a choice between this and the other solution posted, I'd recommend this one since it is a good amount faster on average.
0

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')})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.