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
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
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.
You can split first by ,
, then convert to array again and split again by /
str.split(",").join("/").split("/")
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.
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);
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));
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