Skip to content

Convert each word in a string to hashtags in JavaScript

We can hashtag every word in a string in JavaScript by splitting by space and prepend # to every word.

Advertisements
//Input
let str = "The quick brown fox jumps over the lazy dog";

//Output
let hashtags = "#The #quick #brown #fox #jumps #over #the #lazy #dog"

Here’s the code snippet.

const str = 'The quick brown fox jumps over the lazy dog';
const hashtags = (str, char) => {
   return str
   .split(" ")
   .map(word => `${char}${word}`)
      .join(" ");
};

console.log(hashtags(str, '#'));

//#The #quick #brown #fox #jumps #over #the #lazy #dog

This works with a single word too.

const word = 'Poopcode';
console.log(hashtags(word, '#'));

//Poopcode

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.