3

I am working on a javascript project and got an issue.
I have values like this: 1231+, 83749M, 123199B I can get the numeric values/number only by doing this:

var theNumber = parseInt(1231+);

But how can I get the trailing characters like: +, M, B? I can't use substring because there can be more than one character. But characters will be always at the trail.

5 Answers 5

7
var orig = "1231+";
var theNumber = parseInt(orig);
var theChar = orig.replace(theNumber, "");

Replacing "1231" in "1231+" with "" leaves "+".

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

1 Comment

You are welcome. (I love regex myself, but it is overkill for something like this.)
1

You could use an regular expression. Somhow like this:

var string = "1234+";
var regexp = /([0-9]+)(.*)/;
var result = regexp.exec(string);

The result will be:

[ '1231+',
  '1231',
  '+',
  index: 0,
  input: '1231+' ]

So result[1] will then be your number and result[2] your suffix.

Comments

1

use regular expressions:

Expression for you is : [\d]

Get all non numeric characters.

Code example

$(document).ready(function() {
    var elem = '1234+';
    alert(elem.replace(/\d/g, ''));
});

//Result +

2 Comments

It's worth explaining how the user can use regular expressions. Give a code example of how this could be put into practice.
The only issue with this is that there could be a character in the middle of the string too - which it appears that the OP might not want.
1

If all you're concerned about is trailing characters and not worried if there are alphabetic characters in the middle of the string then you could use this regex -

[^\d]*$

A handy tool for regex testing is http://regexpal.com/

Given that we have a pattern, we can now match that -

var foo = '1231+';
var trailers = foo.match(/[^\d]*$/);
console.log(trailers);

Comments

0

Try this code

var n1 = "234234M",
    n2 = "6546D",
    n3 = "4455+";
alert(n1.replace(parseInt(n1), ""));
alert(n2.replace(parseInt(n2), ""));
alert(n3.replace(parseInt(n3), ""));

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.