views:

54

answers:

3

Let's say I have these two strings: "5/15/1983" and "1983.05.15". Assume that all characters in the string will be numeric, except a "separator" character that can appear anywhere in the string. There will be only one separator character; all instances of any given non-numeric character in the string will be identical.

How can I use regex to extract this character? Is there a more efficient way than the one below?

"05-15-1983".replace(/\d/g, "")[0];

Thanks!

+3  A: 
"05-15-1983".match(/\D/)

Technically, this returns an array containing one string, but it will implicitly convert to the string most places you need this.

Matthew Flaschen
So if we're just looking for THE character, using your code above, it should be: "05-15-1983".match(/\D/)[0][0] then? Is this better than my example? Why?
JamesBrownIsDead
@James, as I said, the above is an array, but implicitly convertible, so you probably don't need the `[0]`. Further, `"05-15-1983".match(/\D/)[0]` and `"05-15-1983".match(/\D/)[0][0]` are *exactly* equivalent. There is no char type, so indexing returns a string. In fact, you can add as many `[0]`s as you want. I do think this answer is better, since your example forces the evaluator to look at every letter, and do (trivial) concatenation. My answer will stop after finding the first non-digit.
Matthew Flaschen
A: 

Clearly tired or not paying attention on my previous answer. Sorry about that. What I should have written was:

var regexp = new RegExp("([^0-9])","g");
var separator = regexp.exec("1985-10-20")[1];

Of course, Matthew Flaschen's works just as well. I just wanted to correct mine.

eldarerathis
`exec` is a function on RegExp, not String, and the returned array has length 1, so 1 is not a valid index.
Matthew Flaschen
I'm clearly tired. I goofed that syntax up a lot.
eldarerathis
And like Matthew's code, yours doesn't need the `"g"` flag for the same reason he stated (in the comments).
slebetman
A: 

Though i could not exactly get what you trying to do i tried to extract the numbers only in one string and the seperator in next string.

I used the above:

<script>
var myStr1 = "1981-01-05";
var myStr2 = "1981-01-05";
var RegEx1 = /[0-9]/g;
var RegEx2 = /[^0-9]/g;
var RegEx3 = /[^0-9]/;
document.write( 'First : ' + myStr1.match( RegEx1 ) + '<br />' );
document.write( 'tooo : ' + myStr2.replace( RegEx2,  "" ) + '<br />' );
document.write( 'Second : ' + myStr1.match( RegEx2 ) + '<br />'  );
document.write( 'Third : ' + myStr1.match( RegEx3 ) + '<br />'  );
</script>

Output:

First : 1,9,8,1,0,1,0,5
tooo : 19810105
Second : -,-
Third : -

I hope you get your answer

KoolKabin