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

2
  • You don't use jquery for that. Commented Sep 11, 2013 at 7:17
  • What do you need this for? What's the next step? Commented Sep 11, 2013 at 7:27

3 Answers 3

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"]
Sign up to request clarification or add additional context in comments.

4 Comments

var r = /\d+/; var str="How are you 10 doing 12 today?"; var n=str.split(r); works
@xanatos I removed the need for filter with the last version
@Eez It wouldn't get the three parts required by OP
@dystroy it will do right? last remaining part after digits will be in 3rd one. But agree that makes it more specific.
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"]

4 Comments

+1 You're right, even if it still needs trimming. Edit : just +1 now :)
[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.
How do I split a string with numeric and symbol like '30%'?
@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.
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"]

4 Comments

You didn't test, I guess.
That simply finds the integer. It doesn't split the string into an array, as he asking.
@dystroy done trim i know lot of code but i was just testing my skills without regex.
@dystroy can you please give some links from where i can learn regex.I know regex but only basics.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.