user815460
user815460

Reputation: 1143

Regex to return single attribute from string

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!!

Upvotes: 2

Views: 4394

Answers (3)

zellio
zellio

Reputation: 32484

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.

Upvotes: 14

Dan Spiteri
Dan Spiteri

Reputation: 1819

Couldn't you just do this?

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

Upvotes: 4

SBSTP
SBSTP

Reputation: 3639

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?

Upvotes: -1

Related Questions