0

I have this string

let str = "name1,name2/name3"

and I want to split on "," and "/", is there is a way to split it without using regexp?

this is the desire output

name1
name2
name3
al12001
  • 23
  • 4

7 Answers7

1

Little bit of a circus but gets it done:

let str = "name1,name2/name3";
str.split("/").join(",").split(",");

Convert all the characters you want to split by to one character and do a split on top of that.

LearningEveryday
  • 584
  • 1
  • 3
  • 13
1

You can split first by ,, then convert to array again and split again by /

str.split(",").join("/").split("/")
Adrian Naranjo
  • 862
  • 6
  • 14
0

Without regexp you can use this trick

str.split('/').join(',').split(',')
Mahdi N
  • 2,128
  • 3
  • 17
  • 38
0

Use the .split() method:

const names = "name1,name2/name3".split(/[,\/]/);

You still have to use a regex literal as the token to split on, but not regex methods specifically.

jonowles
  • 376
  • 3
  • 7
0

Just get imaginative with String.spit().

let str = "name1,name2/name3";
let str1 = str.split(",");
let str2 = str1[1].split("/");
let result = [str1[0],str2[0],str2[1]];
console.log(result);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

If you don't want to use regex you can use this function:

function split (str, seps) {
  sep1 = seps.pop();
  seps.forEach(sep => {
    str = str.replace(sep, sep1);
  })
  return str.split(sep1);
}

usage:

const separators = [',', ';', '.', '|', ' '];
const myString = 'abc,def;ghi jkl';

console.log(split(myString, separators));
Yukulélé
  • 15,644
  • 10
  • 70
  • 94
-1

You can use regexp:

"name1,name2/name3".split(/,|;| |\//); 

this will split by ,, ;, or /

or

 "name1,name2/name3".split(/\W/)

this will split by any non alphanumeric char

Yukulélé
  • 15,644
  • 10
  • 70
  • 94