Kyle Asaff
Kyle Asaff

Reputation: 274

Javascript regex to extract all characters between quotation marks following a specific word

I have the text:

s.events="event3"
s.pageName="Forum: Index"
s.channel="forum"
s.prop1="Forum: Index"
s.prop2="Index Page"
s.prop36=""
s.prop37=""
s.prop38=""
s.prop39=""
s.prop40="53"
s.prop41="Anonymous"
s.prop42="username"
s.prop43=""
s.prop47=""
s.eVar1="Forum: Index"
s.eVar2="Index Page"
s.eVar36=""
s.eVar37=""

saved in a var in javascript and I want to extract the text between the quotes of s.prop42 giving me the result:

"username"

what I have right now is

    var regex = /\?prop.42="([^']+)"/;
    var test = data.match(regex);

but it doesnt seem to work, can someone help me out?

Upvotes: 2

Views: 5520

Answers (2)

Michael Y.
Michael Y.

Reputation: 661

Can't comment on above answer, but I think the regex is better with .* like so:

var myregex = /s\.prop42="(.*)"/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
    thematch = matchArray[1];
}

Upvotes: 0

zx81
zx81

Reputation: 41838

Use this:

var myregex = /s\.prop42="([^"]*)"/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
    thematch = matchArray[1];
} 

In the regex demo, look at the capture group in the right pane.

Explanation

  • s\.prop42=" matches s.prop42=" (but we won't retrieve it)
  • The parentheses in ([^"]*) capture any chars that are not a " to Group 1: this is what we want
  • The code gets the Group 1 capture

Upvotes: 2

Related Questions