Let's say I have the following string:
var str = "The quick brown fox jumped over the lazy dog and fell into St-John's river";
How do I (with jQuery or Javascript), replace the substrings ("the", "over", "and", "into", " 's"), in that string with, let's say an underscore, without having to call str.replace("", "") multiple times?
Note: I have to find out if the substring that I want to replace is surrounded by space.
Thank you
Try with the following:
var newString = str.replace(/\b(the|over|and|into)\b/gi, '_');
// gives the output:
// _ quick brown fox jumped _ _ lazy dog _ fell _ St-John's river
the \b matches a word boundary, the | is an 'or', so it'll match 'the' but it won't match the characters in 'theme'.
The /gi flags are g for global (so it'll replace all matching occurences. The i is for case-insensitive matching, so it'll match the, tHe, THE...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With