3

Existing Url

http://example.com/home.php?id=1&branch_id=4&course_id=5

New url

http://example.com/home.php?id=1&branch_id=4

removing course_id from existing url

How to remove one parameter value from url.

Tried below code:

function replaceUrlParam(url, paramName, paramValue){
    var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
    var newUrl=url
    if(url.search(pattern)>=0){
        newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
    }
    else{
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
    }
    return newUrl
}

but its not working...

2
  • 2
    .replace(/[&?]course_id=\d+/, '') Commented Apr 24, 2017 at 10:45
  • jsfiddle.net/fc0q69dd Commented Apr 24, 2017 at 10:50

2 Answers 2

7

As you said that you want to use variable instead of directly using .replace(/&course_id=\d+/, ''), you can do it like below:-

Example:-

var re = new RegExp("&course_id=\\d+");
var newUrl="http://example.com/home.php?id=1&branch_id=4&course_id=5";
console.log(newUrl.replace(re, ''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

2 Comments

change the code : function RemoveParam(c) { var re = new RegExp("[&\?]"+ c +"=\\d+");} and it work perfectly, thak you for your help..
@Ranju glad to help you :):)
2

You can simply do that by using this code to remove &course_id=5:

var url = "http://example.com/home.php?id=1&branch_id=4&course_id=5";
url.replace(/([&\?]course_id=5*$|course_id=5&|[?&]course_id=5(?=#))/, '');

It will return you: http://example.com/home.php?id=1&branch_id=4

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.