如何在给定字符后选择子字符串

Ala*_*ski 5 javascript regex

我想使用正则表达式将子字符串保存到javascript变量,除非有不同/更简单的方法.例如,我有这样的链接:http: //www.youtube.com/watch?v = sEHN4t29oXY&feature = related

我想只得到sEHN4t29oXY&feature =相关所以我想我必须检查出现的第一个等号然后将该字符串的其余部分保存到变量中..请帮忙,谢谢

Bry*_*eld 10

高效:

variable = variable.substring(variable.indexOf('?v=')+3) // First occurence of ?v=
Run Code Online (Sandbox Code Playgroud)

正则表达式:

variable = variable.replace(/.*\?v=/, '') // Replace last occurrence of ?v= and any characters before it (except \r or \n) with nothing. ? has special meaning, that is why the \ is required
variable = variable.replace(/.*?\?v=/, '') // Variation to replace first occurrence.
Run Code Online (Sandbox Code Playgroud)


小智 3

不是使用正则表达式,但也很简单,因为第一个 url 部分是静态的并且有 23 个符号长度

'http://www.youtube.com/watch?v=sEHN4t29oXY&feature=related'.substr(23)
Run Code Online (Sandbox Code Playgroud)

哦,我犯了一个错误,他想要另一部分,所以实际的代码将如下所示:

'http://www.youtube.com/watch?v=sEHN4t29oXY&feature=related'.substr(31)
Run Code Online (Sandbox Code Playgroud)