Nabin
Nabin

Reputation: 81

jQuery string replace using regex

I have a URL like this:

http://localhost/Customer/Edit/3

I need to check Customer/Edit/3 and replace the 3 with current id (9) in jQuery.

The final URL should look like http://localhost/Customer/Edit/9

Note: the replace must only work for Customer related URL.

How can I do this?

Upvotes: 0

Views: 2205

Answers (1)

MMM
MMM

Reputation: 7310

You don't need jQuery for this:

var pattern = /(http:\/\/localhost\/Customer\/Edit\/)\d/;
var str = "http://localhost/Customer/Edit/3";
str = str.replace(pattern, '$1' + 9);
console.log(str); // returns http://localhost/Customer/Edit/9

The above should be enough for you to create a solution that works for you.

If you have a guarantee that there is only one number in the URL, you can do the following instead:

var pattern = /\d/;
var str = "http://localhost/Customer/Edit/3";
str = str.replace(pattern, 9);
console.log(str);

Upvotes: 1

Related Questions