[Vuejs]-How can I split a string based on three delimiters?

1๐Ÿ‘

โœ…

You can split on multiple strings/characters using | (the or operator) in the regular expression. The snippet has some examples, including \\t or \t (the last being a tab character).

const splitData = str => str.split(/\\t|\n|;|\t/);

const dataClub1 =  "- City\\t- MU\\t- Liverpool\\t- Arsenal\\t- Chelsea"; // \\t
const dataClub2 =  `- City
- MU
- Liverpool
- Arsenal
- Chelsea`; // \n
const dataClub3 =  "- City;- MU;- Liverpool;- Arsenal;- Chelsea"; // ;
const dataClub4 =  `- City\t- MU\t- Liverpool\t- Arsenal\t- Chelsea`; // \t

console.log(splitData(dataClub1));
console.log(splitData(dataClub2));
console.log(splitData(dataClub3));
console.log(splitData(dataClub4));
.as-console-wrapper { top: 0; max-height: 100% !important; }
๐Ÿ‘คKooiInc

0๐Ÿ‘

referring to this answer:
https://stackoverflow.com/a/19313633/4298881

let separators = ['\\\\t', ';', '\\n'];
let regex = new RegExp(separators.join('|'), 'g');
dataClub.split(regex); // ["- City", " - MU", " - Liverpool", " - Arsenal", " - Chelsea"]

๐Ÿ‘คSurely

0๐Ÿ‘

While putting separators in an array(dataClub.split(/[โ€˜\tโ€™,โ€™\nโ€™,โ€™;โ€™]/) will also split the city, since regex is either of them. Making regex to exactly match the separators will help.

let dataClub =  "- City\\t - MU\\t - Liverpool\\t - Arsenal\\t - Chelsea";
const splittedDc = dataClub.split(/\\t|\n|;/);
console.log(splittedDc);
๐Ÿ‘คHemant Kumar

Leave a comment