SparkNee
SparkNee

Reputation: 450

How to split a string by regex while keeping the splitter in the array

I'm starting to learn regex in Javascript, can I do that?

Imagine I have the following string:

Car ball car ball circle happy

And I want to match by all instead of ball, an output like:

["Car", "car", "circle happy"]

Or, split when I find ball in my string:

["Car", "ball", "car", "ball", "circle happy"]

How can I do that?

Upvotes: 1

Views: 888

Answers (2)

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

You can split by 'ball' to get your answer as :

["Car", "car", "circle happy"]

Or by '(ball)' to get your answer as :

["Car","ball","car","ball","circle happy"]

var str="Car ball car ball circle happy";
var vals=str.split(/ball/i).map(String.trim);
console.log(vals);

// Or

var valsAll=str.split(/(ball)/i).map(String.trim);
console.log(valsAll);

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may split with /(ball)/ (or to account for a whole word, add \b word boundary around the pattern). Wrapping the whole pattern with capturing parentheses will output the matched string parts into the resulting array.

var s = 'Car ball car ball circle happy';
console.log(s.split(/(ball)/).map(function(x) { return x.trim();}));

If you do not need the ball to be output in the resulting array, omit the capturing parentheses, use a mere /ball/.

If you need to make the pattern case insensitive, use the /i modifier: /(ball)/i.

Upvotes: 2

Related Questions