简体   繁体   中英

JS: How can I extract a substring after a specific word and a certain number of characters?

let's say I have a URL like:

http://randomsite.com/search?book=1234&chapter=567&pages=0177

Where page count is always four digits, but the book or chapter numbers are ambiguous.


What I want to do is, sometimes from a search, random extra junk might be added after a page query, like session= or referrer= or more. But, I want to cut everything off, no matter what it is, after the string "pages=####".

How would I go about doing that? Thank you!

Try using indexOf and substring :

 const str = "http://randomsite.com/search?book=1234&chapter=567&pages=0177&randomjunk" const strippedStr = str.substring(0, str.indexOf("pages=") + "pages=".length + 4) // always four digits console.log(strippedStr)

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