3

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

4 Answers 4

8

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

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

Comments

1

Use this.

str = str.replace(/\b(the|over|and|into)\b/gi, '_');

1 Comment

if it contained there, it would be _re
0

Use a regular expression.

str.replace(/(?:the|over|and|into)/g, '_');

The ?: is not strictly necessary, but makes the command slightly more efficient by not capturing the match. The g flag is necessary for global matching, so that all occurences in the string are replaced.

I am not exactly sure what you mean by having to find out if the substring is surrounded by space. Perhaps you mean you only want to replace individual words, and leave the whitespace intact? If so, use this.

str.replace(/(\s+)(?:the|over|and|into)(\s+)/g, '$1_$2');

Comments

0

Use regular expression with the g flag, which will replace all occurences:

var str = "The quick brown fox jumped over the lazy dog and fell into the river";
str = str.replace(/\b(the|over|and|into)\b/g, "_")
alert(str)  // The quick brown fox jumped _ _ lazy dog _ fell _ _ river

1 Comment

if it contained there, it would be _re

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.