0

My code like this :

<template>
    ...
        <p v-for="club in clubs">{{club}}</p>
    ...
</template>
<script>
export default {
  data: () => ({
    clubs: ''
  }),
  mounted () {
    let dataClub =  "- City\\t - MU\\t - Liverpool\\t - Arsenal\\t - Chelsea"
    // let dataClub =  "- City\n - MU\n - Liverpool\n - Arsenal\n - Chelsea"
    // let dataClub =  "City;MU;Liverpool;Arsenal;Chelsea"
    let dc = dataClub.split(/[\n;]/)
    this.clubs = dc
  }
}
</script>

dataClub is dynamic. It can be separated with ; and can also be separated with \n. Other than that it can also be separated by the sign \\t

How can I do a split if there are 3 separators?

I try let dc = dataClub.split(/[\n;\\t]/), but it does not works

moses toh
  • 12,344
  • 71
  • 243
  • 443

3 Answers3

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
  • 119,216
  • 31
  • 141
  • 177
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
  • 1,649
  • 16
  • 23
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
  • 186
  • 6