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