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

Asked

Viewed 955 times

7

I want to share the string in 2 parts (will always be a array divide into two parts - or two elements) each time a vertical bar | (only in the first case).

For example: I have a string

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

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

For example:

var string = "João|||23anos|"; <- In this example it will return this array: ["João", "", "", "23anos", ""].

Array I wish I could be printed:

["João", "||23anos|"]

The first vertical bar will only serve to give split and the rest of the vertical bars should be within the array.

8 answers

6

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

Explanation:

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

inserir a descrição da imagem aqui

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

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

  • have any tips to learn regex? from basic to advanced

  • 1

    +1, but it is full match, with "TCH" ;-)

  • @Wtrmute Thank you, had written wrong!

6

Using indexOf to find the first occurrence of the character and split the text, slice, in this position:

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

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

console.log(parts);

4


A very simple way would be to get the length of the first part (João) and then use it to take 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 believe the code is self-explanatory. First it obtains the first part (until the first |), then it uses the length of the text (in this case 4) and sum with 1, then it takes all the text from the fifth character.

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

  • 1

    In JS num would have the equivalent of indexOf? That would be more to the point than using a split

  • I’ll give you positive because I’m the first to give the answer.

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 from split limits the number of divisions.

2

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

2

You may also wish to do so using .shift to pick up the first item and .join to "restore" the remnant as 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: the .split has a parameter called limit:

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

However what it does is limit the results

2

As it comes to the first occurrence, you could do so :

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}') - the replace will replace the first occurrence by our tab {spl}
  • .split('{spl}') - The split will divide the sentence by our separator.

Note

  • {spl} - is merely illustrative, could be a simple $ or @.

0

Using slice and split

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

console.log(resultado);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.