7

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

For Example i have string:

str='123&345&678&910'

If i use the javascripts split, it split it into 4 parts. But i need it to be in 2 parts only considering the first '&' which it encounters.

As we have in Perl split, if i use like:

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

it split's str into 2 parts, but javascript only gives me:

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

i want sec to be:

sec=345&678&910

How can i do it in Javascript.

kailash19
  • 1,771
  • 3
  • 22
  • 39
  • 4
    @ajax333221. It's a good question! Mentioning other language syntax doesn't make it a bad question nor a translation question. – gdoron Jun 22 '12 at 07:03
  • Use `indexOf` to get the index of the first `&`. Then use the `substring` function to extract both parts. But it's impossible to be blocked by this if you google "javascript string functions". – Denys Séguret Jun 22 '12 at 07:04
  • 1
    @gdoron didn't say it wasn't, I just feel he could attempt to do a little more himself. Remember, SO is one of the last options – ajax333221 Jun 22 '12 at 07:05
  • @ajax333221. How do you know he didn't try enough? Crystal ball? and **who said SO is the last option?!** – gdoron Jun 22 '12 at 07:06
  • 1
    possible duplicate of [split string only on first instance of specified character](http://stackoverflow.com/questions/4607745/split-string-only-on-first-instance-of-specified-character) – Yoshi Jun 22 '12 at 07:07
  • @ajax333221: i tried, then after i asked SO. I think SO as always the best option to get if i am not able to :) – kailash19 Jun 22 '12 at 07:12

6 Answers6

6
var subStr = string.substring(string.indexOf('&') + 1);

View this similar question for other answers:

split string only on first instance of specified character

Community
  • 1
  • 1
infojolt
  • 5,244
  • 3
  • 40
  • 82
4

You can use match instead of split:

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

output:

["123", "345&678&910"]
core1024
  • 1,882
  • 15
  • 22
3

You can remain on the split part by 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"
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
1

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 match) or an array with 2 elements (before the split and everything after)

Demo

ajax333221
  • 11,436
  • 16
  • 61
  • 95
1

I have that:

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 convenience:

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 ):[]
               );
}
abuduba
  • 4,986
  • 7
  • 26
  • 43
0

What about the use of split() and replace()?:

Given we have that string 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

Please note that split() returns an array that is why getting the index with first[0] is recommended, however, without getting the index, it still worked as needed i.e first+"&".

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

Hope this helps :)