Extracting a specific part of a string using javascript

First of all, I know that many questions like this have been asked before, but I find it difficult to wrap my head around a regex, so try to explain it if you can.

I have a line that is constantly changing, this: TOKEN (SwapToken) - 1005.00000127 TOKEN

Only the number changes, it can change as soon as 1005.00000128

or 1500.001

, and I created a program to extract the string when I need it. The only thing I need is I need to highlight / extract only the number, or maybe extract a string and then create another variable containing only the number.

Will the encoding look different because the number might be changed? How can I extract just numbers? Whether Regex is the best option, I know there may be several others.

thank

+3


source to share


1 answer


Here's a simple regex you can use

/\d+\.\d+/g

It does make assumptions about your input though. Basically, nothing in it will look like a decimal number.

\ d means any digit (0 - 9)
\. means literal period (.)
+ means one or more previous characters

You need a backslash because in regex a. means match with any character, so you need to avoid it.



This particular regexp finds everything that looks like a decimal number by finding everything 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))
      

Run codeHide result


You can check regular expressions here. He had some neat features. And explains what your regex on the right side is doing.

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

+6


source







All Articles