Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Match then Replace

4:10 pm on Jul 18, 2009 (gmt 0)

Full Member

10+ Year Member

joined:Jan 27, 2005
posts: 229
votes: 0

When I do both the match and replace functions, my script stops working. How do I do a match and replace sequentially?

var youtube = 'http://www.youtube.com/watch?v=44xb9nb2P7g';
var youtube = youtube.match(/=(\w{11})/g);
var youtube = youtube.replace(/=/,'');

(In the example I'm trying to get the last 11 characters following the equal sign.)

9:22 am on July 19, 2009 (gmt 0)

Preferred Member

5+ Year Member

joined:Aug 18, 2008
votes: 0

.match() returns either an array of found match/matches or null, so if the returned match is not null, access by index number. Try:

var youtube = 'http://www.youtube.com/watch?v=44xb9nb2P7g';
youtube = youtube.match(/v=(\w+)/);
youtube = (youtube !== null) ? youtube[0].replace(/v=/,'') : null;