2015-08-08 85 views
2

我有一个变量,在第一次出现数字时需要分割一次,导致出现alpha和numeric分量。Javascript第一次出现时会分裂一次

情况#1

var str = "S44.5"; 
I need the output to be "S" and "44.5" 

情况#2

var str = "44.5"; 
I need the output to be "" and "44.5" 

我如何能做到这一点的JavaScript?请帮忙!

回答

2

使用正则表达式

Regular Expression DEMO

var text= "hello12"; 
var text= "s4.44"; 
var text= "4.53"; 
var text= "aaa4.53"; 

var matches = text.match(/([a-zA-Z]*)([0-9\.]+)/); 
+1

http://jsfiddle.net/dtouqooa/1/ –

+0

太棒了! –

+0

不客气! – CyC0der

2

这种分裂的信号之前,它还包括如果情况不是这样,一个空字符串。

enter image description here

var a = /([a-z]*)([\w.]+)/i.exec("S44.5"); 
 
var b = /([a-z]*)([\w.]+)/i.exec("44.5"); 
 

 
console.log("I need the output to be %s and %s", JSON.stringify(a[1]), JSON.stringify(a[2])) 
 
console.log("I need the output to be %s and %s", JSON.stringify(b[1]), JSON.stringify(b[2]))