开发者

JavaScript regex: find non-numeric character

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(/\开发者_C百科d/g, "")[0];

Thanks!


"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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜