I have a string like this:
const string = 'We have this 8/8 / 69 structure in the text/another text and we want to grab it'
and I want to return the part of text which are numbers between slashes. the structure I want is this:
' 8 /8 / 69 '
Number/Number/Number
Note that it could be untrimed:
' 8/ 8 / 69 '
or
'8/8/69'
I tried to split the string by /
and return the structure but the issue is I want to be sure that only the Number/Number/Number
returns.
You can use a simple /[0-9]+ *\/ *[0-9]+ *\/ *[0-9]+/
regex:
[0-9]+
: 1 or more digits *
: any number of spaces\/
: a /
\
is necessary to mean "a litteral /
", because /
bounds the regex, see the snippet below)var t = "We have this 8/8 / 69 structure in the text/another text and we want to grab it and 1/2/3";
console.log(t.match(/[0-9]+ *\/ *[0-9]+ *\/ *[0-9]+/g));
(note that in this snippet I used the g
modifier to find multiple occurrences)
If you want to limit copy-paste, or have a need to accept series of 1 to n numbers, you can use a repetition operator:
/[0-9]+( *\/ *[0-9]+){2}/ # 3 numbers (1 number then exactly 2 slash-and-number)
/[0-9]+( *\/ *[0-9]+){1,4}/ # 2 to 5 numbers