Adib Aroui
Adib Aroui

Reputation: 5067

Replace last numbers from a string

I have a string url with following structure:

url/inbox/g/{page_number}

I am in a situation where I need to replace {page_number} with a new value. So I need somehow to search for url/inbox/g and replace it with url/inbox/g/{new_value}.

How to use replace() function to achieve this?

Upvotes: 0

Views: 545

Answers (5)

SaidbakR
SaidbakR

Reputation: 13534

Due to the number is the last portion of the string, you may use non regex solution using lastIndexOf and slice:

<script>
  url = 'url/inbox/g/44';
  replaceNumStr = 'Dummy';
  newVal = url.slice(0,url.lastIndexOf('/')+1);
  alert(newVal+replaceNumStr);
 </script>

Checkout this demo

Upvotes: 1

Xotic750
Xotic750

Reputation: 23472

Two other possibilities, not using RegExp.

const url = 'url/inbox/g/{page_number}';
const parts = url.split('/', 3);
const new_number = '{new_page_number}';
parts.push(new_number);
const new_url1 = parts.join('/');
console.log(new_url1);

const url = 'url/inbox/g/{page_number}';
const new_number = '{new_page_number}';
const new_url2 = `${url.slice(0, url.lastIndexOf('/'))}/${new_number}`;
console.log(new_url2);

Upvotes: 1

Thomas W.
Thomas W.

Reputation: 450

I would use the following regular expression : /\/\d*$/m And the replacement could be done with :

str.replace(/\/\d*$/m, "/" + n)

Where n is the new value

The regular expression says find everything that match "/" followed by 0 or more digits and which end the string. Reference

Upvotes: 1

larz
larz

Reputation: 5766

var url = "url/inbox/g/4321"
var your_number = 1234
url = url.replace(/\d+$/, your_number)

Upvotes: 1

Use a replace statement like this:

var newVal  = 'anything',
    pattern = "/url\/inbox\/g\/\d+$/",
    reg     = new RegExp(pattern, "i");
    repURL  = url.replace(reg, "url/inbox/g/" + newVal);

I am assuming url is dynamically accessed.

Upvotes: 1

Related Questions