Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace all substrings in strings

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

like image 830
user765368 Avatar asked Aug 08 '26 09:08

user765368


1 Answers

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...

like image 115
David Thomas Avatar answered Aug 09 '26 22:08

David Thomas