Reputation: 9055
I have the following url
example.com/p/deals&post_id=3
where post id is a get variable. I would like to sanitize the url string and the returned result should be
example.com/p/deals
I have been trying to use JavaScript's .replace
but because of the get variable at the end of url, doesn't seems to work. How would I build a regex to exclude this substring.
Upvotes: 2
Views: 3268
Reputation: 598
To match all chars after and including the first & you would use the pattern
\&(.*)
and simply replace with an empty string.
the JS would be
var urlString = "example.com/p/deals&post_id=3";
var searchP = "\&(.*)" ;
var replaceP = "" ;
var rEx = new RegExp( searchP, urlString ) ;
var replacedText = sourceText.replace( rEx, replaceP ) ;
Upvotes: 3
Reputation: 61842
A regex is not needed for this. Simply split the string and take the first string from the array:
var str = "example.com/p/deals&post_id=3";
var san = str.split("&")[0];
Here's a working fiddle.
Upvotes: 3