Lately iv'e been trying to find some ways to manipulate a string (for some project of mine) and i'm having a hard finding something that will mach my case.
usually the string will include 3 numbers (can also be decimal - that's what make it more complicated) and separated by 1 / 2 signs ("-", "x", "*" and so on...)
i did some research online and found this solution (which i thought it was good)
.match(/\d+/g)
when i tried it on some case the result was good
var word = "9-6x3"
word = word.match(/\d+/g)
it gave me array with 3 indexes, each index held a number ['9', '6', '3']
(which is good), but if the string had a dot (decimal number) this regex would have ignored it.
i need some regex which can ignore the dots in a string but can achieve the same result.
case =
var word = "9.5-9.3x7"
output = ['9.5', '9.3', '7']
Asked
Active
Viewed 228 times
0

Àtishking
- 263
- 1
- 4
- 15
-
`['9,5', ...]` looks wrong. because `[...9.3, 7]` part looks like a real pattern – zer00ne Apr 19 '20 at 12:41
-
@zer00ne i made an edit. anyway the type of the indexes in the array doesnt really matter – Àtishking Apr 19 '20 at 12:42
2 Answers
0
Here is a simple regex that suits your requirement,
/\d+\.?\d*/g

Ramaraja
- 2,526
- 16
- 21
-
-
this will also match if there are multiple decimal points (like word="9...5-7" gives `[ '9...5', '7' ]` – Always Learning Apr 19 '20 at 12:50
-
that still doesn't work. if word="9.5-7" you get `[ '9.5' ]` and miss the 7 – Always Learning Apr 19 '20 at 12:54
-
-
@RamarajaRamanujan I just checked AlwaysLearning answer and it seems like it fits better to what i need, but thank you anyway. – Àtishking Apr 19 '20 at 12:55
0
Try this regular expression to allow for an optional decimal place:
word.match(/\d+([\.]\d+)?/g)
This says:
- \d+ - any number of digits
- ([\.]\d+)? - optionally one decimal point followed by digits

Always Learning
- 5,510
- 2
- 17
- 34