Reputation: 2551
I wants to remove alphabet from string. In my string variable it will have the numbers with alphabet
For example
var myString = '1122D'
// I want remove the last alphabet only from the above variable
var myString = '1122Z3'
// I want remove the `Z3` from above string
var myString = '112DD2'
// I want remove the `DD2` from above string
I know how to replace specific character using .replace('','')
. But in my case it is different
Upvotes: 3
Views: 824
Reputation: 3240
Best way -
myString.slice(0, myString.indexOf(myString.match(/[a-zA-Z]/)));
Upvotes: 0
Reputation: 14541
You can use regex /([\d]+).+$/g
as well:
var regex = /([\d]+).+$/g;
console.log(regex.exec("1122D")[1]);
regex.lastIndex = 0;
console.log(regex.exec("1122Z3")[1]);
regex.lastIndex = 0;
console.log(regex.exec("112DD2")[1]);
Upvotes: 0
Reputation: 54
use this code:
myString.substr(0,myString.search('[a-zA-Z]'));
Upvotes: 2
Reputation: 15351
If the strings are always made up starting with numbers and you want to get the number up until the first alphabetical character, I'd recommend the use of parseInt()
since its behaviour is exactly that it parses numeric characters in a string to a number until it encounters the first non-numeric character where it stops parsing.
var myNumber = parseInt(myString);
Upvotes: 3