简体   繁体   中英

extracting specific part of string with javascript

First of all, I know lots of questions like this have been asked before, but it is hard for me to wrap my head around regex so please try to explain it if you can.

I have a string that changes constantly, it is: TOKEN (SwapToken) - 1005.00000127 TOKEN

Only the number changes, it could vary as little as to 1005.00000128 or to 1500.001 , and I have created a program to extract the string when I require. The only things is, I need to isolate/extract only the number, or maybe extract the string and then create another variable containing just the number.

Would the coding look different because the number is subject to change? How I could accomplish extracting only the number? Is Regex the best option, I know there might be a few others.

Thank you

Here's a simple regex you can use

/\\d+\\.\\d+/g

Although it makes assumptions about your input. Mainly that nothing else in it will look like a decimal number.

\\d means any digit (0 - 9)
\\. means a literal period (.)
+ means one or more of the preceding characters

You need the backslash because in regex a . means match any character, so you have to escape it.

This particular regex finds anything that looks like a decimal number by finding anything that looks like one or more digits followed by a "." followed by one or more digits.

 let str = "TOKEN (SwapToken) - 1005.00000127 TOKEN" let num = str.match(/\\d+\\.\\d+/g)[0]; console.log(parseFloat(num)) 

Here's a site where you can test regular expressions out. It's got some neat features. And explains what your regex is doing on the right side

https://regex101.com/r/8RuY3A/1

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