1

I have strings with version numbers like:

"1.4.2.57"
"8.4.3"
"3.12.0.25"

I only need the first 3 numbers, I was going to use substr, but if the numbers are > 9 the substr will fail.

How can I extract x.x.x from strings like (x.x - x.x.x - x.x.x.x) where x is = [0-99]

1
  • ^(\d+)\D+(\d+)\D+(\d+) should do it, you'll have to translate that to javascript regex though. You'll have the first 3 digits with any delimiters in your first three capture groups, you can change \D+ to (?:\s|-|\.)+ if you want to specify .,-, and space as your only valid delimiters with none capturing groups. Commented Jun 20, 2011 at 21:04

2 Answers 2

2
var t = [
    "1.4.2.57",
    "8.4.3",
    "3.12.0.25"
    ];
for (var v = 0; v < t.length; v++){
    var ver = t[v].split('.');
    alert(ver.slice(0,3).join('.'));
}

Split by ., then slice to get only first 3 digits (in this case elements, since they were split to an array), then rejoin with . again.

Sign up to request clarification or add additional context in comments.

2 Comments

Cool, it even works when the version is like "1.5", I though he slice would show an error but it doesn't.
@riviraz: Correct, slice will silently grab as much as it can, leaving you with only the desired portions.
0
var no_periods = string.replace('.', '');
var new_string = no_periods.substr(0,2);

will get rid of all the periods and then just get the first three numbers, is that what you wanted?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.