简体   繁体   中英

How would you extract a part (pattern) of a string in javascript

I have a string like this "Token: 1830-5868-4807-2907-3850, Units: 36.2, Debt Amount: 0.00, Debt Remaining: 0, Recept No: 84657081"

I want to get just this 1830-5868-4807-2907-3850

Use slice method:

const str = "Token: 1830-5868-4807-2907-3850, Units : 36.2, Debt Amount : 0.00, Debt Remaining : 0, Recept No: 84657081"

const result = str.slice(6, 31)

console.log(result) // output: '1830-5868-4807-2907-3850'

You can use a (non-greedy) regex to grab the sequence between "Token: " and the first comma:

const str = "Token: 1830-5868-4807-2907-3850, Units : 36.2, Debt Amount : 0.00, Debt Remaining : 0, Recept No: 84657081";
const token = str.match('Token: (.*?), .*')[1];

Assuming you will have only one sub string matching the pattern you can use string.match

 const paragraph = "Token: 1830-5868-4807-2907-3850, Units: 36.2, Debt Amount: 0.00, Debt Remaining: 0, Recept No: 84657081"; const regex = /\d{4}-\d{4}-\d{4}-\d{4}-\d{4}/g; const found = paragraph.match(regex); console.log(found[0]);

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