Home > Net >  How do I separate tags in a string
How do I separate tags in a string

Time:08-03

I am currently using .split to try to split a string into different 'tags'.

let text = "@yusra is cool @zain @chris is cool";
const myArray = text.split("@");
console.log(myArray);

The code above gives this output:

Array ["", "yusra is cool ", "zain ", "chris is cool"]

the expected output is:

Array ["yusra", "zain ", "chris"]

How do I modify this to make it do what I want.

CodePudding user response:

Use match with a regex. Here we match @ and then one or more lowercase letters between "a" and "z".

const text = "@yusra is cool @zain @chris is cool @bob";
console.log(text.match(/@[a-z] /g));

CodePudding user response:

Instead of using split you can use match to find the tags via a regex.

let text = "@yusra is cool @zain @chris is cool";
const myArray = text.match(/@\w /g);
console.log(myArray);

CodePudding user response:

Chain together what you need to complete the task. Splitting on space seems to be a better option, then filter only those that have '@' and mapping to remove the '@'.

let text = "@yusra is cool @zain @chris is cool";
const myArray = text.split(' ').filter(s => s.startsWith('@')).map(s => s.slice(1))
console.log(myArray);

CodePudding user response:

You could try something like this:

let text = "@yusra is cool @zain @chris is cool";
const myArray = text.split(" ").filter(s => s.startsWith("@")).map(s => s.substring(1));
console.log(myArray);

  • Related