使用jquery在其中按整数拆分字符串

时间:2013-09-11 07:16:40

标签: javascript jquery regex

我有很长的字符串

"When I was 10 year old"

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

在不同情况下整数可能不同,句子也可能会改变。

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

如何在Jquery / java-script

中使用正则表达式与split进行共轭

3 个答案:

答案 0 :(得分: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"]

答案 1 :(得分: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"]

答案 2 :(得分:0)

你可以用这个

DEMO

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