最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to return single attribute from string - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Jul 9, 2011 at 7:48 pavium 15.1k4 gold badges34 silver badges50 bronze badges asked Jun 30, 2011 at 20:15 user815460user815460 1,1433 gold badges11 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 14

something like:

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

should match

the tailing " is for pleteness 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.

Couldn't you just do this?

document.getElementById("my_div").getAttribute("key")
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?

发布评论

评论列表(0)

  1. 暂无评论