bitecoder
bitecoder

Reputation: 55

Regex: get number formated n.n.n from string using javascript?

I am trying to get number i.e. 1.0.3 from string . I only want numbers that are formatted with two dots and have ver# before them. Is my regex implementation correct. It is work but will it fail in any condition?

var str = "https://example.x.y.com/z/ver#1.5.0"; 
var res = str.match(/ver#.\.(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)/g);
return res;

https://jsfiddle.net/tthfkzjt/

Upvotes: 1

Views: 154

Answers (1)

user2705585
user2705585

Reputation:

I am trying to get number i.e. 1.0.3 from string . I only want numbers that are formatted with two dots and have ver# before them

This could be done by simple regex: /ver#(\d+\.\d+\.\d+)/

Capture the first group using \1 or $1.

Regex101 Demo

JS Fiddle

var str = "https://example.x.y.com/z/ver#1.5.0"; 
var res = str.match(/ver#(\d+\.\d+\.\d+)/);
document.getElementById("res").innerHTML = res ? res[1] : "";
<div id="res"/>

Upvotes: 1

Related Questions