3

Example Text:

<div id="not-wanted">
no no 
no 
</div>
<div id="wanted">I want 
only this 
text
</div> no no no
no no
<div id="not-wanted">
no no no 
</div>
<div id="wanted">no no
no no</div>
<div id="wanted">
no no     
</div>

Should deliver:

I want 
only this 
text

Or better:

I want only this text

Unfortunately, my solution catches the 2 delimitation strings also:

$('#put').append(/<div id="wanted">[^<>]*<\/div>/.exec(strg)[0]);

==>

<div id="wanted">I want 
only this 
text
</div>

Online example

http://regex101.com/r/rF7jR9

Question

What regular expression for Java Script can deliver the characters between delimiting strings, if there are also \n and \r resend. It would be nice, if \n and \r are removed from the delivered string. The RegExpr should work fast.

2
  • 3
    Why using regex? In this example, you have object "div" with known ID. you can use getElementById('wanted').innerHTML to get the content. Commented Mar 20, 2014 at 11:24
  • If the example text is in strg. How to use it? var txt = strg.getElementById('wanted').innerHTML is not working. Commented Mar 20, 2014 at 21:21

2 Answers 2

11

Now I know how to:

$('#put').append(/<div id="wanted">([\s\S]*?)<\/div>/.exec(strg)[1]);

Thank you Jerry for the (group) hint. [\s\S] stands for every character. *? stop after first found <\/div>.

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

1 Comment

excellent, thank you - very useful for finding blocks of comments that all start with a specific string when refactoring, since in my case I certainly did not want to remove all comments everywhere!
1

You can use a capture group and ignore the full match?

$('#put').append(/<div id="wanted">([^<>]*)<\/div>/.exec(strg)[1]);
                                   ^------^                    ^

( ... ) is a capture group and since it's the first one in the regex, it gets to the first capture group, hence the 1 near the end.

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.