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
3
  • 2
    '...without using regexp' may I ask: why? Commented Apr 17, 2020 at 23:05
  • This has been answered before check this: stackoverflow.com/a/36976348/13331933 Commented Apr 17, 2020 at 23:08
  • I have data with a lot of different separators, and I was wondering if there is cleaner way to split it, like using "or" or something like that Commented Apr 17, 2020 at 23:16

7 Answers 7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

str.split(",").join("/").split("/")

Comments

0

Without regexp you can use this trick

str.split('/').join(',').split(',')

Comments

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.

Comments

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);

Comments

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));

Comments

-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

1 Comment

"...split it without using regexp?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.