MD. ABDUL Halim
MD. ABDUL Halim

Reputation: 722

How to get data from last number and still before space in javascript using regular expression

This is my problem below

var id = "10101-Building and Construction  21";

Basically, I have got id's data from other calculation , i want to separate to 21.

Here result will be 21;

How can i remove id's value without 21 .

Please any help?

Upvotes: 0

Views: 138

Answers (3)

Somnath Kharat
Somnath Kharat

Reputation: 3610

$(document).ready(function(){
var id = 10101-Building and Construction  21;
var result=id.substring(id.Length-2,id.Length)
});

Upvotes: 0

GeekyCoder
GeekyCoder

Reputation: 428

Assumptions made based on your question :

- The id you wana extact from the string is always at the last
- The id is always a number

  • If above assumptions are true :
  • then you can write a javascript function and perform the following functions.

    1. loops from the last and check for numbers till it finds a string

    2. as soon as it encouters a character it stops and you get the requiered id

the function in javascript

function express()
{
var str="10101-Building and Construction  21";
var temp,id;
for(var t2=1;t2<=str.length;t2++)
{
    temp = str.substring(str.length-t2);

    var condition = isNaN(temp);
    if(condition == true)
    {
        break;
    }
    id=temp;
}
document.write("<br>"+id);
}

this will extract the id

and the result:

id = 12

Click Here : And the fiddle for a live example of this based on your values

Upvotes: 0

Robin Leboeuf
Robin Leboeuf

Reputation: 2116

Maybe combining substring and lastindexOf, something like:

var result = id.substring(id.lastIndexOf(' ')+1);

Upvotes: 1

Related Questions