split / regex only on the first vertical bar "|"

7

I want to split the string into 2 parts (it will always be a array divide into two parts - or two elements) whenever a vertical bar | first case).

For example: I have a string

var string = "João|23anos";

I can give string.split("|") and return will be an array ["João", "23 anos"] . But I'd like to give split only in the first case of vertical bar | and copy the rest of string to the array ;

For example:

var string = "João|||23anos|";

asked by anonymous 28.06.2017 / 19:45

8 answers

4

A very simple way would be to get the length of the first part ( João ) and then use it to pick up all the rest.

For example:

texto = "João|||23anos|";
partes = [];

partes.push( texto.split('|')[0] );
partes.push( texto.substring(partes[0].length + 1) );

console.log(partes);

I think the code is self-explanatory. First it gets the first part (up to the first | ), then it uses the length of the text (in this case 4) and adds it to 1, so it takes all text from the fifth character.

As commented, you can only use indexOf , ignoring split , as answered by @Anderson Carlos Woss

    
28.06.2017 / 19:54
6

Using indexOf to search for the first occurrence of the character and divide the text, slice , into this position:

const text = "João|||23anos|";

let firstMatch = text.indexOf('|');
let parts = [text.slice(0, firstMatch), text.slice(firstMatch+1)];

console.log(parts);
    
28.06.2017 / 20:01
6

var str = 'João|||23anos|';
var splits = str.match(/([^|]*)\|(.*)/);
splits.shift();
console.log(splits);

Explanation:

  • str.match(/([^|]*)\|(.*)/); returns 2 Groups plus Full Match , then the Array will contain the text plus the 2 groups:

  • Use shift() to remove the first element of Array which is Full Match .

If you wanted to test some Regex recommend using this tool Regex101 .

    
28.06.2017 / 19:59
2

You can also do this by using .shift to get the first item and .join to "restore" the rest as a string again:

var str = "João|||23anos|";

//Divide a string
var results = str.split('|');

//Pega o primeiro resultado
var first = results.shift();

//Unifica os resultados restantes em uma nova string
var last = results.join('|');

//Cria um array baseado nos resultados
var result = [first, last];

console.log(result);
  

Note: or .split has a parameter called limit :

str.split([separator[, limit]])
     

However what it does is limit the results

    
29.06.2017 / 00:08
2

var string = "João|||23anos|";

var ret = string.split(/\|(\|*\s*[\w.]+\s*\|*)/, 2);

console.log(ret);

Explaining:

In the regexp the vertical bar ( | ) will be our separator and in parentheses what we want to capture.

The second argument of split limits the number of divisions.

    
28.06.2017 / 20:25
2

texto = "João|||23anos|";
console.log(texto.split(/\|(.*)/,2));
    
30.06.2017 / 15:47
2

As this is the first occurrence, you could do this:

text = "João|||23anos|";
console.log(text.replace('|', '{spl}')); // SUBSTITUI A PRIMEIRA OCORRENCIA
console.log(text.replace('|', '{spl}').split('{spl}')); // DIVIDE PELO SEPARADOR

Explanation

  • .replace('|', '{spl}') - replace will replace the first occurrence with our {spl}
  • .split('{spl}') - split will split the sentence through our separator.

Note

  • {spl} - is merely illustrative, could be a simple $ or @ .
29.06.2017 / 14:01
0

Using slice and split

var texto = "João|||23anos|";
var resultado = texto.split("|", 1).concat([texto.slice(texto.indexOf("|") + 1)]);

console.log(resultado);
    
29.06.2017 / 22:44