0

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 ]/);
asked Nov 5, 2013 at 10:34
3
  • remove jquery wrapping.. it will work fine Commented Nov 5, 2013 at 10:37
  • @Mr_Green: No, it won't. Commented Nov 5, 2013 at 10:41
  • yeah it will not work.. Commented Nov 5, 2013 at 10:47

5 Answers 5

2

Just use the string as separator (with spaces)

.split(' IN ');
answered Nov 5, 2013 at 10:38

Comments

1

/[ 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] : '');
answered Nov 5, 2013 at 10:39

3 Comments

That's working except that if one of them is empty I get undefined as the value of the string.
or simply splitter[1] || ''
@thg435 That'd work just as fine (the reason for this, OP, is that splitter[1], if not set, would be undefined which is a falsy value. Therefore what this would say is "if splitter[1] is not falsy, then use splitter[1], but if it IS falsy, then use ''".)
0

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

string.split('IN');
answered Nov 5, 2013 at 10:38

Comments

0

Why you use jQuery function here? Just work with string

'Software Sheffield'.split(' IN ');
answered Nov 5, 2013 at 10:41

Comments

0

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/

Harry
90k26 gold badges215 silver badges223 bronze badges
answered Nov 5, 2013 at 10:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.