0

Well the answer should be very simple.But i am new to the regular expression.

What i want to do is just find and replace :

Eg: iti$%#sa12c@#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters

In the above sentence replace the words "of" with "in"

I tried this but didn't get the result, please help me out.

string="iti$%#sa12c@#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters";
var string2=string.replace("/(\w*\W*)of(\w*\W*)/g","$1in$2");
console.warn(string2);

5 Answers 5

4

Fix the regex literal (no quotes) and use word boundaries (\b, no need to use $1 and $2) :

var string2 = string.replace(/\bof\b/g, "in");
Sign up to request clarification or add additional context in comments.

Comments

2

Why not a simple var replaced = yourString.replace(/of/g, 'in');?

1 Comment

This doesn't replace "words", as this would also match "of" when not a complete word.
1

Globally replace without using a regex.

function replaceMulti(myword, word, replacement) {
    return myword.split(word).join(replacement);
}

var inputString = 'iti$%#sa12c@#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters';

var outputString = replaceMulti(inputString, 'of', 'in');

2 Comments

Also, this is not Haskell.
This doesn't replace "words", as this would also match "of" when not a complete word.
0

Like this?

str.replace("of","in");

2 Comments

This will replace only one occurence, not all
This also doesn't replace "words", as this would also match "of" when not a complete word.
0

Regular expressions are literals or objects in JavaScript, not strings.

So:

/(\w*\W*)of(\w*\W*)/g

or:

new Regexp("(\\w*\\W*)of(\\w*\\W*)","g");

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.