2

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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 ) ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.