4

I have long string like

"When I was 10 year old"

I have to get this string split to an array: ["When I was", "10" , "year old"].

The integer can be different in different cases and the sentence may also change.

In short i want to split a string by integer in it Is it possible?

How can i use regex in conjugation with split in Jquery/java-script

xdazz
  • 158,678
  • 38
  • 247
  • 274
Kuttan Sujith
  • 7,889
  • 18
  • 64
  • 95

3 Answers3

8

You can use

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

Result :

["When I was", "10", "year old"]
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

The regexp you're looking for is as simple as

/\D+|\d+/g

Example:

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

To get rid of spaces:

> str.split(/(?:\s*(\d+)\s*)/g)
["When I was", "10", "year old"]
georg
  • 211,518
  • 52
  • 313
  • 390
  • +1 You're right, even if it still needs trimming. Edit : just +1 now :) – Denys Séguret Sep 11 '13 at 07:35
  • 1
    [just saying] if the number is first then it is adding a empty element in the array which can be avoided using `filter` function as shown in this [**link**](http://stackoverflow.com/a/2843625/1577396). – Mr_Green Sep 11 '13 at 07:53
  • How do I split a string with numeric and symbol like '30%'? – thednp Oct 05 '14 at 15:21
  • @georg no need, it surelly gonna get marked as duplicate, but I figured, it's num = str.split('%') but I am not sure if num[1] is gonna be the '%', bcz I also need that. – thednp Oct 05 '14 at 15:28
0

you can use this

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"]
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107