4

我有很长的字符串

"When I was 10 year old"

我必须将此字符串拆分为数组:["When I was", "10" , "year old"]

整数在不同的情况下可能不同,句子也可能发生变化。

简而言之,我想在其中按整数拆分字符串有可能吗?

如何在 Jquery/java-script 中使用正则表达式与 split

4

3 回答 3

8

您可以使用

var str = "When I was 10 year old";
var arr = str.match(/(\D*)\s(\d*)\s(\D*)/).slice(1);

结果 :

["When I was", "10", "year old"]
于 2013-09-11T07:20:00.703 回答
4

您正在寻找的正则表达式很简单

/\D+|\d+/g

例子:

> str = "When I was 10 year old"
"When I was 10 year old"
> str.match(/\D+|\d+/g)
["When I was ", "10", " year old"]

摆脱空格:

> str.split(/(?:\s*(\d+)\s*)/g)
["When I was", "10", "year old"]
于 2013-09-11T07:33:28.650 回答
0

你可以用这个

演示

var r = /\d+/;
var str = "When I was 10 year old";
var x = $.trim(str.match(r).toString());
var str_split = str.split(x);
var arr = [];
$.each(str_split, function (i, val) {
    arr.push($.trim(val));
    arr.push(x.toString());
});
arr.pop();
console.log(arr); // ["When I was", "10", "year old"]
于 2013-09-11T07:18:00.113 回答