Cameron
Cameron

Reputation: 28823

JavaScript regex spltting of string if keyword exists

I have two possible example strings:

'Software Sheffield'

and

'Software IN Sheffield'

and I want to split the string if it has the keyword 'IN' in the middle of it.

So for example 1:

var string1 = 'Software Sheffield';

var string2 = '';

and for example 2:

var string1 = 'Software';

var string2 = 'Sheffield';

Can anyone help me achieve this?

So far I have tried:

var string1 = string.split(/[ IN ]+/);

var string2 = string.split(/+[ IN ]/);

Upvotes: 0

Views: 63

Answers (5)

Althaf M
Althaf M

Reputation: 508

Why dont you try

 var strings = "Software IN Sheffield".split(" IN "); // this will be returning an array

 var string1 = strings[0];

 var string2 = strings[1];

check this http://jsbin.com/iKeCUnA/1/

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39542

/[ IN ]+/ means "the individual characters [SPACE]/I/N/[SPACE] repeated 1 to inifinity times" so it'd also match "NINININININIII NNNNIIINIIII".

You can simply use a string in split():

var splitter = string.split(' IN ');
var string1 = splitter[0];
var string2 = (splitter.length >= 2 ? splitter[1] : '');

Upvotes: 1

akrasman
akrasman

Reputation: 83

Why you use jQuery function here? Just work with string

'Software Sheffield'.split(' IN ');

Upvotes: 0

MC ND
MC ND

Reputation: 70943

Just use the string as separator (with spaces)

.split(' IN ');

Upvotes: 2

lukas.pukenis
lukas.pukenis

Reputation: 13597

Your regex - [ IN ] Means that it matches I letter and N letter. Simply

string.split('IN');

Upvotes: 0

Related Questions