Reputation: 3154
Very simple thing, but can't find it anyways.. How can i limit a regexp result?
Example string:
io=G4-WfdxQHfBLrcB7AAAC; connect.sid=s%3AKdRP6Bh_bFsN_9Br4TfTykVSqenUgpDA.ighSSEVvoIInT%2Fc7z%2B2HaQQRzwS6p7gkEqJs2ZQbw1k; sid=s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo
My current regexp:
/\ssid=(.*)/
Current result is:
sid=s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo
Desired result is:
s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo
How can i improve that?
Upvotes: 1
Views: 89
Reputation: 26667
You can use the first capture group as
match = str.match(/\ssid=(.*)/);
// match[0] will contain match after the `=`
Or more simply you can write
match = str.match(/\ssid=(.*)/)[1];
Example
str = "io=G4-WfdxQHfBLrcB7AAAC; connect.sid=s%3AKdRP6Bh_bFsN_9Br4TfTykVSqenUgpDA.ighSSEVvoIInT%2Fc7z%2B2HaQQRzwS6p7gkEqJs2ZQbw1k; sid=s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo"
match = str.match(/\ssid=(.*)/)[1];
// Output
// => s%3ACte80repoZLXoDfMqABqrNcg9qdO0a5L.1I%2BFc61dYeyqNhmjxCVMiZEPgLvgolvMIohLAx22WYo
From MDN
(x)
Matches x and remembers the match. These are called capturing parentheses.
For example, /(foo)/ matches and remembers "foo" in "foo bar". The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.
Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).
Upvotes: 1