I am new to regex and have this cdn url that returns text
and I want to use javascript to match and extract the version number. I can match the latestVersion but I am not sure how to get the value inside of it.
ex on text
:
...oldVersion:"1.2.0",stagingVersion:"1.2.1",latestVersion:"1.3.0",authVersion:"2.2.2"...
I tried doing this line to display latestVersion:"1.3.0
but not successful
const regex = /\blatestVersion:"*"\b/
stringIneed = text.match(regex)
And I only need 1.3.0
not including the string latestVersion:
CodePudding user response:
You could use a lookbehind, or a capturing group like this:
const str = '...oldVersion:"1.2.0",stagingVersion:"1.2.1",latestVersion:"1.3.0",authVersion:"2.2.2"...'
console.log(
str.match(/(?<=latestVersion:")[^"] /)?.[0]
)
console.log(
str.match(/latestVersion:"([^"] )"/)?.[1]
)
CodePudding user response:
Try adding a capture group ()
to match certain strings in the Regex.
/\blatestVersion:"([0-9.] )"/
CodePudding user response:
There are many ways of doing it. This is one:
const text='...oldVersion:"1.2.0",stagingVersion:"1.2.1",latestVersion:"1.3.0",authVersion:"2.2.2"...';
console.log(text.match(/latestVersion:"(.*?)"/)?.[1])
The .*?
is a "non-greedy" wildcard that will match as few as possible characters in order to make the whole regexp match. For this reason it will stop matching before the "
.