Consider the following:
考虑以下:
var string = 'https://awesome-site.com/page/#s-in=ascending'
var regex = /(s-in=)([\w.-]+)/g
var match = string.match(regex)
console.log(match)
// this returns: s-in=ascending
// Using replacement patterns, it's possibl to select
// a subset of the string selected via the regex
var subset = '
Consider the following:
考虑以下:
var string = 'https://awesome-site.com/page/#s-in=ascending'
var regex = /(s-in=)([\w.-]+)/g
var match = string.match(regex)
console.log(match)
// this returns: s-in=ascending
// Using replacement patterns, it's possibl to select
// a subset of the string selected via the regex
var subset = '$1' + 'new-string'
var match = string.replace(regex, subset)
cosnole.log(match)
// this returns: s-in=new-string
I'm trying to figure out how to return the string after the equals sign via regex (ideally the one in the example above, because the original string, a URL, is potentially quite complex).
我正在尝试找出如何通过regex在等号后面返回字符串(理想情况下是上面示例中的字符串,因为原始的字符串URL可能非常复杂)。
Question:
问题:
How to return a subset of the regex-matched string, e.g.: the part after the =?
如何返回正则匹配字符串的子集,例如:=后面的部分?
3 个解决方案
#1
3
Use the exec method and get the captured groups like this:
使用exec方法,并得到这样的捕获组:
var re = /(s-in=)([\w.-]+)/g;
var str = 'https://awesome-site.com/page/#s-in=ascending';
while ((m = re.exec(str)) !== null) {
alert(m[2]);
}
Here, m[2] will hold the value ascending (the contents of the 2nd capturing group).
在这里,m[2]将保持值升序(第二个捕获组的内容)。
Note that if you are matching literal text, you do not have to capture it (here, s-in=). Adding unnecessary capture groups means unnecessary overhead. So, we'd better use /s-in=([\w.-]+)/g regex and refer to the text after = with m[1].
请注意,如果您是匹配文字文本,则不需要捕获它(这里,s-in=)。添加不必要的捕获组意味着不必要的开销。因此,我们最好使用/s-in=([\w -]+)/g regex,并在= m[1]之后引用文本。
#2
0
If you use exec, it will return an array containing all the captured groups and the full match.
如果您使用exec,它将返回一个包含所有捕获组和完整匹配的数组。
var string = 'https://awesome-site.com/page/#s-in=ascending'
var regex = /(s-in=)([\w.-]+)/g
regex.exec(string); //returns: ["s-in=ascending", "s-in=", "ascending"]
#3
0
// below line will create the new object of RegExp constructor.
var (variable name) = new RegExp('Your Regular expression'),
// now create another variable to hold the substring that will match
// for that (created Object)'s method called ".exec()" use by passing "string you want to match" as a parameter.
(sub string variable name) = (variable name).exec('string that you want to match');
For Example
例如
var temp = new RegExp('/(s-in=)([\w.-]+)/g'),
substring = temp.exec('https://awesome-site.com/page/#s-in=ascending');
' + 'new-string'
var match = string.replace(regex, subset)
cosnole.log(match)
// this returns: s-in=new-string
var string =