Shafizadeh - 2 years ago 62
Javascript Question

# How do I match the numbers sequence rising?

I have a string contains just numbers. Something like this:

var numb = "5136789431235";

And I'm trying to match ascending numbers which are two or more digits. In string above I want this output:

var numb = "5136789431235";
// ^^^^ ^^^

Actually I can match a number which has two or more digits:
/[0-9]{2,}/g
, But I don't know how can I detect being ascending?

Try this to match consecutive numbers

var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]

DEMO

var numb = "5136789431235";

var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]

document.body.innerHTML += JSON.stringify(matches,0,4);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download