w00
w00

Reputation: 26812

Get string and number with regex

I have a string in javascript like this:

some string 27

or it could be

some string

or

string 123

or even

string 23A - or - string 23 A

So in other words, it's always a string. Sometimes it ends with a number, sometimes not. And sometimes the number has a letter (only one) at the end.

Now the problem is, that I have to split this string. I need the string and number (including the letter if there's one) stored in two variables. Like in:

some string 27

var str = "some string" var number = 27;

I probably need to do this with regex. But i have no idea how.

Can someone please help me out with this?

Upvotes: 0

Views: 186

Answers (5)

Yshayy
Yshayy

Reputation: 325

You could do it with a function:

function splitStringsNumbers(str)
{
    return 
    {
         Numbers: str.match(/[0-9]+/g)
         Strings: str.match(/^[0-9]+/g)
    }
}

Now use it like this:

var obj = splitStringsNumbers("string 23A")
console.log(obj.Strings[0]); //print string
console.log(obj.Numbers[0]); //print 23
console.log(obj.Numbers[1]); //print A

If you want the nubmer as numeric variable, you could use parseInt(str). Also, this solution works only for Integers, for using it with floats (like string 23.4A) you need to change a bit the regex.

Upvotes: 1

fajter
fajter

Reputation: 76

According to what you provided regex should be:

/(.*) (\d+ ?[A-Z]?)$/i

Anything can be string. Number is anchored to the end, it is separated from string by single space, space and letter at the end are optional.

var v='some string 27';
var arr = v.match(/(.*) (\d+ ?[A-Z]?)$/i);
var str = arr[1];
var num = arr[2];

Upvotes: 1

anubhava
anubhava

Reputation: 786091

You should use this regex:

var arr = s.match(/^(\D+?)\s*(\d+(?:\s+[A-Z])?)$/i);

Then use:

var str = arr[1];
var number = arr[2];

Assuming s is your variable containing original text;

Upvotes: 1

eyurdakul
eyurdakul

Reputation: 912

Try this;

var r = new RegExp("/[0-9]+\w?/");
var s = "some letters 125a";
console.log(s.match(r));

Upvotes: 0

hsz
hsz

Reputation: 152294

Try with following regex:

/^([^\d]*)(\d+\s*[a-z]?)?$/i

Upvotes: 0

Related Questions