简体   繁体   中英

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?

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

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM