继续昨天的问题
4523425432NB,32423TY,4NT,43232423432YT,
对于以上的字符,最后两位是字母,前面是数字,位数不定,怎么把数字和字母分别取出.
昨天因为逗号也是字符串里面的内容,所以输出的自然也有逗号!~~~
今天我继续研究学习
1.我首先想到的是先去掉逗号,再这样做分割
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>split</title>
</head>
<body>
<!--4523425432NB,32423TY,4NT,43232423432YT,
对于以上的字符,最后两位是字母,前面是数字,位数不定,怎么把数字和字母分别取出-->
<script>
var str = "4523425432NB,32423TY,4NT,43232423432YT,";
var str2 = str.replace( /[,]/g,"");
var ms = str2.split(/(\d+)([a-zA-Z]{2})/);
for(i = 0; i < ms.length; i++) {
document.write(ms[i]+ "<br />");
}
</script>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>split</title>
</head>
<body>
<!--4523425432NB,32423TY,4NT,43232423432YT,
对于以上的字符,最后两位是字母,前面是数字,位数不定,怎么把数字和字母分别取出-->
<script>
var str = "4523425432NB,32423TY,4NT,43232423432YT,";
var str2 = str.replace( /[,]/g,"");
var ms = str2.split(/(\d+)([a-zA-Z]{2})/);
for(i = 0; i < ms.length; i++) {
document.write(ms[i]+ "<br />");
}
</script>
</body>
</html>
输出结果:
4523425432
NB
32423
TY
4
NT
43232423432
YT
会发现其中有一行空行,因为我开始用replace把字符串中的“,”好替换成“” 所以变成了空格,还是不符合要求
2.接着,我想我可以先用split讲字符串明显的区别“,”来将字符串先分割
再对分割的数组进行查找到我需要的字母输出,需要的数字输出
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>split</title>
</head>
<body>
<!--4523425432NB,32423TY,4NT,43232423432YT,
对于以上的字符,最后两位是字母,前面是数字,位数不定,怎么把数字和字母分别取出-->
<script>
var str = "4523425432NB,32423TY,4NT,123456789YT,";
var ms = str.split(/[,]/);
for(i = 0; i < ms.length-1; i++) {
var reg = /\d+/;
var reg2 = /[a-zA-Z]{2}/;
var num = ms[i].match(reg);
var letter = ms[i].match(reg2);
document.write(num + "<br />");
document.write(letter + "<br />");
}
</script>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>split</title>
</head>
<body>
<!--4523425432NB,32423TY,4NT,43232423432YT,
对于以上的字符,最后两位是字母,前面是数字,位数不定,怎么把数字和字母分别取出-->
<script>
var str = "4523425432NB,32423TY,4NT,123456789YT,";
var ms = str.split(/[,]/);
for(i = 0; i < ms.length-1; i++) {
var reg = /\d+/;
var reg2 = /[a-zA-Z]{2}/;
var num = ms[i].match(reg);
var letter = ms[i].match(reg2);
document.write(num + "<br />");
document.write(letter + "<br />");
}
</script>
</body>
</html>
输出结果:
4523425432
NB
32423
TY
4
NT
123456789
YT
总算符合要求了!~~~不知道是不是有更好的方法呢!~~~