Lewis
Lewis

Reputation: 14866

js - get piece of string

I'm in a trouble with getting product version.

For example, I have 3 pieces of string:

string 1 : version 2.1.3.1

string 2 : ver 21.3.4

string 3 : v 10.2.1

How could I get number 2 in string 1, 21 in string 2 and 10 in string 3 with a single function?

Upvotes: 0

Views: 163

Answers (3)

Amit Joki
Amit Joki

Reputation: 59232

Regex isn't always bad

Use this:

function getMajorVersion(str){
    var matches = str.match(/\d+/); return matches && matches[0];
}

If you are worried about performance, use my answer instead of Allen Chak.

Here is jsperf: http://jsperf.com/regex-vs-native-in-simple-case

Upvotes: 2

friedi
friedi

Reputation: 4360

function getProductVersion(str) {
    return str.match(/\d+/g).map(function(v) { return parseInt(v, 10) });
}

Now you can use this to get the major version:

var version = getProductVersion('version 2.1.3.1');
var majorVersion = version[0];

Upvotes: 0

Allen Chak
Allen Chak

Reputation: 1950

Try this

function getMajorVersion(versionStr){
    var tmp = versionStr.split(' ');
    var v = tmp[1].split('.');
    return v[0];
}

Upvotes: 4

Related Questions