0

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?

3
  • If it is some string 27 A how do you want your 2 variables to be? Commented Feb 8, 2012 at 8:44
  • @anubhava Then it should still consist of two variables. var str = "some string" and var number = "27 A" Commented Feb 8, 2012 at 8:49
  • well "27 A" is not really a number, can you use some better naming variable pls :) Commented Feb 8, 2012 at 8:51

5 Answers 5

1

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;

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

Comments

1

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]; 

Comments

1

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.

Comments

0

Try with following regex:

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

Comments

0

Try this;

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.