Ansjovis86
Ansjovis86

Reputation: 1545

How to split on multiple character pattern in js?

I have this string:

string = 'addition and subtraction 1';

I want to split this string on spaces except when there's a number after a space. So like this:

['addition','and','subtraction 1']

How do I do this?

Upvotes: 1

Views: 590

Answers (3)

vipin
vipin

Reputation: 2510

try this :

string = "addition and subtraction 1".split(/ (?!\d)/g));

output:

["addition", "and", "subtraction 1"]

Upvotes: 1

Parveen Kumar
Parveen Kumar

Reputation: 342

See This:

 var str="addition and subtraction 1";
    var splitstr=str.split(/ (?!\d)/g);
    console.log(splitstr)

Upvotes: 2

Scoots
Scoots

Reputation: 3102

A negative lookahead in your split regex accomplishes this

console.log('addition and subtraction 1'.split(/ (?!\d)/g));

Upvotes: 5

Related Questions