Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose a substring after given character

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/watch?v=sEHN4t29oXY&feature=related

I want to only get sEHN4t29oXY&feature=related so i guess i would have to check for the first equal sign to appear and after that save the rest of that string into the variable.. please help, thanks

like image 597
Alan Budzinski Avatar asked Oct 21 '11 17:10

Alan Budzinski


2 Answers

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.
like image 93
700 Software Avatar answered Nov 15 '22 04:11

700 Software


Like so:

var match = /\?v=(.+)/.exec(link)[1];
like image 25
gilly3 Avatar answered Nov 15 '22 04:11

gilly3