View Single Post
Old 01-09-2013, 06:13 PM   PM User | #3
007julien
Regular Coder

 
Join Date: May 2012
Location: France
Posts: 115
Thanks: 0
Thanked 17 Times in 15 Posts
007julien is an unknown quantity at this point
You have to use a regular expressions (defined with to / delimiters or new RegExp(string)) with the methods : replace, match or test (which simply return a boolean on success).

Some caution is needed with addresses that contain special characters such as dots (which represents any characters in regular expressions and must be preceded by a backslash to regain their initial sense) and slashes (the delimiters which must too be preceded by a backslash).
Then the right syntax could be
Code:

// To replace youtube.com by youtube.com/feed/subscriptions
var url="http://www.youtube.com/foobar";
var newUrl=url.replace(/youtube\.com/,'youtube.com/feed/subscriptions');
alert(newUrl)
// To test for youtube.com/feed/subscriptions"
var url="youtube.com/feed/subscriptions/foobar"
alert(/youtube\.com\/feed\/subscriptions/.test(url))
EDIT : With the constructor var rgx=new RegExp("myString") there is an other problem with backslashes (which mean in a string : the following characters is a control character). Then they should be doubled !

Last edited by 007julien; 01-10-2013 at 10:27 AM..
007julien is offline   Reply With Quote