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 ]/);
-
remove jquery wrapping.. it will work fineMr_Green– Mr_Green2013年11月05日 10:37:29 +00:00Commented Nov 5, 2013 at 10:37
-
@Mr_Green: No, it won't.T.J. Crowder– T.J. Crowder2013年11月05日 10:41:40 +00:00Commented Nov 5, 2013 at 10:41
-
yeah it will not work..Mr_Green– Mr_Green2013年11月05日 10:47:26 +00:00Commented Nov 5, 2013 at 10:47
5 Answers 5
Just use the string as separator (with spaces)
.split(' IN ');
Comments
/[ 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] : '');
3 Comments
splitter[1] || ''
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 ''
".)Your regex - [ IN ] Means that it matches I letter and N letter. Simply
string.split('IN');
Comments
Why you use jQuery function here? Just work with string
'Software Sheffield'.split(' IN ');
Comments
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/