Home > database >  Generate hashtags from string in JavaScript
Generate hashtags from string in JavaScript

Time:03-10

I have a string from an input named 'text' and from this one, I would like to generate hashtags for a different field in my mongoose model:

req.body.tags = req.body.text
  .split('#')
  .map((tag) =>
    tag.trim().replace(/  /g, ' ').split(' ').join('-').toLowerCase()
  )
  .filter((tag) => tag.length !== 0)

The code above is almost perfect but every time, I press a comma it gets inserted as a hashtag(or part of it) which is something I'm trying to avoid as well, take a look into what I'm talking about:

{
    "text": "Hola, mi nombre es Kevin y tu como te llamas? #random, #userundefined"
}

The text above is the data I insert via Postman and this is the output:

"tags": [
  "hola,-mi-nombre-es-kevin-y-tu-como-te-llamas?",
  "random,",
  "userundefined"
],

What I would like to get is this:

"tags": [
  "random",
  "userundefined"
],

I just want to retrieve the words followed by a # and just that, I don't want the commas after it as shown in the random tag

CodePudding user response:

You might want to trim the commas off the ends of your tags after you split:

.map((tag) => {
  let newTag = tag.trim().replace(/  /g, ' ').split(' ').join('-').toLowerCase();
  if (newTag.endsWith(',')) {
    newTag = newTag.substring(0, newTag.length - 1);
  }
  return newTag;
})

EDIT: If you're trying to get rid of anything that isn't preceded by a hashtag, you need to do your split a little differently. I would recommend maybe looking for .indexOf('#') and using .substring() to remove anything up to that index, then do your split.

CodePudding user response:

matchAll should be usefull here...

The demo below is based on the documentation example. It returns an array of match arrays Could be results for regex groups). In your case, you want the result[0] of each matches, therefore the additional map.

let text = "Hola, mi nombre es Kevin y tu como te llamas? #random, #userundefined"

let result = [...text
  .matchAll(/#\w /g)]
  .map(match => match[0])
  
console.log(result)

  • Related