2

Using javascript, can someone please help me with a pattern to match something in this string:

div style="display: none" key="ABC\jones" displaytext="Tom Jones"

My goal is to extract the value for key, in this case: ABC\jones

So, everything between

key="

and

"

Thanks for the help!!

3 Answers 3

14

something like:

/ key="([^"]*)"/

should match

the tailing " is for completeness so that it matches key="..." and not just key="...

As for how this is working, the normal characters are them selves, the [^"] defines a match group of all characters that are not " ( the ^ being not ). So this will match everything after a key=" until it collides with a ". The ( ) capture the matched values for later recall.

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

3 Comments

+1 But / key="([^"]*)"/ (leading whitespace) should be considered. I'm not going to make the remark about all the trouble that HTML + regex is bound to give :)
It works; thanks very much. can you please help me understand how it works. By the way, it seems to also work without the last double quote character.
It works like this: ( ) is a capture group, * means repeat looking for characters inside the [] character group, ^" means "not speechmark" so it just keeps going until it hits the end ".
4

Couldn't you just do this?

document.getElementById("my_div").getAttribute("key")

1 Comment

This will get the id of an element that is already in the DOM. If you need to get it from an HTML string, the regex match method (above) is the way to go.
-1
var str = 'div style="display: none" key="ABC\jones" displaytext="Tom Jones"';

var start = str.indexOf('key="') + 'key="'.length;
var end = str.indexOf('"', start + 1);

var result = str.substring(start, end);

That works... Does it have to be using regex?

2 Comments

Again, str.indexOf(' key="') + ' key="'.length.
Thanks, I agree, but I'd like to use a regular expression :-)

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.