Splitting Javascript into splitting a string into 2 parts, regardless of the number of saliva characters present in a string

I want to split a string in Javascript using the split function into 2 parts.

For example, I have a line:

str='123&345&678&910' 

If I use javascripts split, he broke it into 4 parts. But I need it to be in 2 parts, only taking into account the first "&". with which he is faced.

As with Perl, if I use:

 ($fir, $sec) = split(/&/,str,2) 

it splits str into 2 parts, but javascript only gives me:

 str.split(/&/, 2); fir=123 sec=345 

I need a section:

 sec=345&678&910 

How can I do this in Javascript.

+7
source share
6 answers

You can use match instead of split :

 str='123&345&678&910'; splited = str.match(/^([^&]*?)&(.*)$/); splited.shift(); console.log(splited); 

exit:

 ["123", "345&678&910"] 
+4
source
 var subStr = string.substring(string.indexOf('&') + 1); 

See the same question for other answers:

split the string only by the first instance of the specified character

+6
source

You can stay on the split part using the following trick:

 var str='123&345&678&910', splitted = str.split( '&' ), // shift() removes the first item and returns it first = splitted.shift(); console.log( first ); // "123" console.log( splitted.join( '&' ) ); // "345&678&910" 
+3
source

I wrote this function:

 function splitter(mystring, mysplitter) { var myreturn = [], myindexplusone = mystring.indexOf(mysplitter) + 1; if (myindexplusone) { myreturn[0] = mystring.split(mysplitter, 1)[0]; myreturn[1] = mystring.substring(myindexplusone); } return myreturn; } var str = splitter("hello-world-this-is-a-test", "-"); console.log(str.join("<br>")); //hello //world-this-is-a-test​​​ 

The output will be either an empty array (not a coincidence), or an array with 2 elements (before splitting and just after)

Demo

+1
source

I have:

 var str='123&345&678&910'; str.split('&',1).concat( str.split('&').slice(1).join('&') ); //["123", "345&678&910"] str.split('&',2).concat( str.split('&').slice(2).join('&') ); //["123", "345", "678&910"]; 

for comfort:

 String.prototype.mySplit = function( sep, chunks) { chunks = chunks|=0 &&chunks>0?chunks-1:0; return this.split( sep, chunks ) .concat( chunks?this.split( sep ).slice( chunks ).join( sep ):[] ); } 
+1
source

What about using split() and replace() ?:

Given that we have this line str='123&345&678&910' We can do

  var first = str.split("&",1); //gets the first word var second = str.replace(first[0]+"&", ""); //removes the first word and the ampersand 

Note that split() returns an array, so getting the index with first[0] recommended , but without getting the index, it still works as needed, i.e. first+"&" .

Feel free to replace "&" with the string you need to split.

Hope this helps :)

0
source

All Articles