How to choose a substring after given character

后端 未结 4 834
我寻月下人不归
我寻月下人不归 2021-01-18 18:12

I would like to save a substring to a javascript variable using regex unless there is a different/easier way. For example i have a link like this: http://www.youtube.com/wa

4条回答
  •  隐瞒了意图╮
    2021-01-18 18:13

    Efficient:

    variable = variable.substring(variable.indexOf('?v=')+3) // First occurence of ?v=
    

    Regular expression:

    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.
    

提交回复
热议问题