Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate alphabetic characters from a string with javascript

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.

like image 565
Imrul.H Avatar asked May 09 '26 01:05

Imrul.H


2 Answers

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

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

like image 94
Andy G Avatar answered May 11 '26 15:05

Andy G


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.

like image 28
Prior99 Avatar answered May 11 '26 14:05

Prior99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!