Channa Channa - 1 month ago 6
Javascript Question

How to split string by given sub string?

I have a string as follows

string fullText ="hello";
string givenCharacters ="hel";


after splitting

result=["hel","lo"];


I want to break it to a two parts from a given characters.

for example i want to break above word using "hel"

how can I do that? appreciate any help

Edit:
another example

string fullText ="someText";
string givenCharacters ="som";

after splitting

result=["som","eText"];

Answer

Try this approach

var fullText ="hello";
var givenCharacters ="hel";
var output = fullText.split( givenCharacters ).map( function(item, index, arr){ 
    if ( index == arr.length - 1 ) 
    { 
      return item; 
    } 
    else
    { 
      return item + givenCharacters  
    } 
});
console.log( output );