2

I tried to use regex replace method to replace xxx="yyy" pattern of text in given string like.

My pattern is : /^[a-zA-Z0-9.;:|_-]+="[a-zA-Z0-9.;:_-]+\"/

Code:

var userinput = '<div id="c16430" style="color:red;" class="css-btn">';         
var pattern = /^[a-zA-Z0-9.;:|_-]+="[a-zA-Z0-9.;:_-]+\"/;
userinput = userinput.replace( pattern, "Replaced..." );

But it is not working... jsfiddle. What is wrong?

Thanks in advance..

3
  • 1
    The operator ^ is used to say that you're search at the beggining of the subject, in your case, it have not to be used because you're search any place of the string. Commented Oct 10, 2013 at 13:34
  • Anyway, everytime you need to deal with regex with JavaScript test it on RegexPal Commented Oct 10, 2013 at 13:37
  • 1
    I would recommend you re-tag this "javascript" instead of "jquery" Commented Oct 10, 2013 at 13:39

3 Answers 3

5

You have a couple of problems:

  1. You are trying to match the start of the input, using ^ at the start
  2. You are not using the global flag /g at end, so it would only replace the first match.

This will work:

var pattern = /[a-zA-Z0-9.;:|_-]+="[a-zA-Z0-9.;:_-]+\"/g;

Here is your updated example

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

3 Comments

Didn't like Muse but you deserve +1 haha
@DontVoteMeDown: Ha! I only usually get "btw, Muse are awesome!", but thanks for seeing past your hatred ;-)
@musefan haha i'm just kidding.
2

Simplified for you. As stated this could match false input, not knowing how strict your input is.

var pattern = /[^ =]+="[^"]+"/g;

or ignore non-word characters

var pattern = /[^\W]+="[^"]+"/g;

or stick with the original idea, the i modifier is used to perform case-insensitive matching.

var pattern = /[a-z0-9_.|:;-]+="[^"]+"/ig;

1 Comment

Actually, your regex will match false positives. Consider this input: <div id="c16430" style="color:red;" class="css-btn">="a"</div>. Of course, we don't know how strict the input html is in the OP's case, so it may work perfectly well for them... this is why I avoided trying to improve the regex, and just pointed out the problems with the OP's example
0

It is perfect

/\s[^=]+\=\".*?\"/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.