Javascript regex help

Folks;

I need some help on my regex. Given a string such as “1234-abc” or “1234 abc” or “1234abc”, I simply want to use a regex that splits the string into two parts. i.e. “1234” and “abc”. So the output would be an array like so: array[0] = “1234” and array[1] = “abc”.

Here is my current code which works fine for the number part, but does not handle the text part correctly.


 <html>

<head>

<script type="text/javascript">

function doit(){
var input   = "1234-abc";
var number= input.match(/\\d+/)[0];      //this currently prints 1234
var text = input.match(/[\\w]{0,200}\\d/)[0];  //but this prints abc1234

document.write(number);
document.write(text);

}

doit();

</script>
</head>
<body>

</body>
</head>

Actually I got it working now like so:


var number= input.match(/\\d+/)[0];      
var text = input.match(/[a-zA-Z]+$/)[0];  

function doit(){ 
var input   = "1234-abc"; 
var text = input.match(/(\\d+)|(\\w+)/g);  //but this prints abc1234 
document.write(text[0]); 
document.write(text[1]); 

} 

The most efficient way to do it is by using two capture groups within the regular expression.

What you want is to capture numbers at the start (\d+)
and for there to be an optional space or a dash [ \-]?
and to then capture some word characters (\w+)

Which ends up being:


var match = input.match((/\\d+)[ \\-]?(\\w+)/),
    // match[0] is the complete string that fits with the regular expression
    // match[1] is the first capture group, from (\\d+)
    number = match[1],
    // match[2] is the second capture group, from (\\w+)
    text = match[2];