0

I would like to match this regexp in javascript:

com\..*</div>

As you can see I want to have com. and then anything and then </div>. But in javascript this is not working, it always founds the com/jdksf</div> not the com.fdsfd<div> text. Any idea why is that?


Edit: My code looks like this:

var patt1=new RegExp("com\..*</div>");
alert(patt1.exec(document.getElementsByTagName("body")[0].innerHTML));
4
  • 1
    Post your actual code please - can't tell anything from such a short description. Commented Nov 25, 2010 at 10:47
  • The code you included in your edit doesn't have any \escape characters at all Commented Nov 25, 2010 at 10:53
  • Added, I used this \escape, but it isn't working Commented Nov 25, 2010 at 10:53
  • you need a double escape because it's a string, see my answer below :) Commented Nov 25, 2010 at 10:54

1 Answer 1

5

You need to escape the ., like this:

var patt1=new RegExp("com\\..*</div>");

The double backslash is because it's a string, so \\. is really \. in the regex. Or, declare it as a regex object directly:

var patt1 = /com\..*<\/div>/;

You can test both versions here.

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

5 Comments

won't solve the problem though - '.' matches anything, including the literal '.' character.
@Benubird - this is escaping it, so it's \. in the end, which is a literal match.
Right, what I meant was, if it's not matching com.foo with com..*, changing it to con\..* won't help - but I see I misread the question, your solution is correct in this case. +1
I think this will be ok, I just have some problem, hold on, I try to resolve it.
Does it matter if I have a line break before the </div>. I don't think so.

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.