0

I have a string that contains an html document. I need to know if this string contains the substring <title>Anmelden - Text</title>. Unfortunately there are some new lines in the string, so that the string looks like this:

...
<title>
        Anmelden - Text
</title></head>
...

I have tried the following code:

var idx = html.search( /<title>\n*.*Anmelden.*\n*<\/title>/ );

But idx is always -1. If I remove the <title>and </title>the expression works.

I have used http://regexpal.com/ to verify my regex. There it works on my input.

What am I doing wrong?

6
  • 4
    Don't use a regex for this. Create a DOM element and add the HTML string to it. Then, you can manipulate it like any DOM element, i.e. use getElementsByTagName() to get the title. Commented Oct 6, 2014 at 8:09
  • 1
    @Martin try <title>[\S\s]*?Anmelden[\S\s]*?<\/title> Commented Oct 6, 2014 at 8:14
  • Instead of searching for .*, use \s|\S or [^] or some such hack to match ANY character including newline. Commented Oct 6, 2014 at 8:16
  • @Avinash Your suggestion worked. If you post an answer instead of a comment I will gladly accept it. Commented Oct 6, 2014 at 8:30
  • @Amal Your suggestion will work of course, but I don't need anything else of the document. My suspicion would be that creating an html doc and looking for the title is much more overhead than the regex approach. Correct me please if I am wrong. Commented Oct 6, 2014 at 8:35

1 Answer 1

3

Use [\S\s]* instead of \n*.* and .*\n* because there may be a possibility of spaces after the newline character. Note that \n matches only the newline character but \s matches all the space characters including newline \n , carriage return \r, tab characters \t also.

<title>[\S\s]*?Anmelden[\S\s]*?<\/title>
Sign up to request clarification or add additional context in comments.

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.