user1092395
user1092395

Reputation: 65

jQuery - How to select specific element inside text?

I have some text lines like that :

Is it possible to select with jQuery the last numbers after the second "^" and remove the other part ?

ie keeping the last number of each lines like this :

I know how to select class / id / specific text but i hang up here. thank in advance

Upvotes: 1

Views: 154

Answers (3)

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

var string = 'vt_wildshade2^508^508',
    number = string.match(/[0-9]+$/)[0];
console.log(number);

$: Matches end of string.
[0-9]: Matches numbers.
+: Matches the preceding 1 or more times.
*: Mathes the preceding 0 or more times.
You can change + to * if you are not sure if it has numbers in the end of the string, this case number will be an empty string.

Demo using +
Demo using *

Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

Upvotes: 1

Austin
Austin

Reputation: 6034

If the format will always be the same, you can use javascript's String.split(delimiter) method to split the string at the '^' into an array, which will return something like:

    ["vt_wildshade2", "508", "508"]

In this case, the following code would take the last bit from your line:

    var str = "vt_wildshade2^508^508";
    var numbers = str.split("^")[2];

For reference:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

If the format will not always be the same, it will be required to use regular expressions to find the data that you want in the format that you need it, as other answerers have explained.

Not sure how this data is coming in, could you clarify on how this data is displayed before the script is run?

Upvotes: 1

artlung
artlung

Reputation: 34013

IF you have:

vt_wildshade2^508^508

Say, from:

var theText = $('p').text();

So, equivalent to:

var theText = 'vt_wildshade2^508^508';

You can get the final "508" text with:

var finalNumber = theText.split('^')[2];

And if you need it to be a numer, something more like:

var finalNumber = (theText.split('^').length > 2) ? parseInt(theText.split('^')[2], 10) : -1;

If there is no 3rd number, the default is -1 in the code above.

Upvotes: 0

Related Questions