I need to split a sentence, but only by a first concurrence. For ex:
"hello my dear hello blah blah".split('ello')
Expected result:
["h", "o my dear hello blah blah"]
I need to split a sentence, but only by a first concurrence. For ex:
"hello my dear hello blah blah".split('ello')
Expected result:
["h", "o my dear hello blah blah"]
You could match ell
with a non greedy search and take only the groups left and right from it.
String#split
does not work here, because it works global for the string.
console.log("hello my dear hello blah blah".match(/^(.*?)ell(.*)$/).slice(1));
Using a variable (mind special characters!) and a RegExp
constructor.
var string = 'ell',
regexp = new RegExp('^(.*?)' + string + '(.*)$');
console.log("hello my dear hello blah blah".match(regexp).slice(1));
You can look for the first index of the occurance of your search string, then split the original on that index, like so:
const sentence = "hello my dear hello blah blah"
const searchValue = 'ell';
const index = sentence.indexOf(searchValue);
const result= []
result.push(sentence.slice(0, index));
result.push(sentence.slice(index+ searchValue.length));
// result = ["h", "o my dear hello blah blah"]
Replace with something that will not be in the string, and split by it :
console.log( "hello my dear hello blah blah".replace('ello', '\0').split('\0') )