Split a string with an integer in it using jquery

I have a long string like

"When I was 10 year old" 

I need to pass this string to an array: ["When I was", "10" , "year old"] .

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

In short, I want to split the string into an integer. Is this possible?

How can I use regex in conjunction with split in jquery / java-script

+4
source share
3 answers

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

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"] 
+8
source

The regular expression you are 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
source

Source: https://habr.com/ru/post/1501601/


All Articles