function wrapHashtagsInText(text) {
const words = text.split(' ');
const processedWords = words.map((word) => {
const isHashTag = word.startsWith('#');
if (!isHashTag) {
return word;
}
const hasWordPunctuationMarks = word.includes('?') || word.includes('!') || word.includes('.') || word.includes(',');
if (!hasWordPunctuationMarks) {
return `<span>${word}</span>`;
}
const punctuationMarkIndex = word.split('').findIndex((letter) => '?!,.'.includes(letter));
const firstPartOfWord = word.slice(0, punctuationMarkIndex);
const lastPartOfWord = word.slice(punctuationMarkIndex);
return `<span>${firstPartOfWord}</span>${lastPartOfWord}`;
});
return processedWords.join(' ');
}
console.log(wrapHashtagsInText('My favourite language is #javascript because I love #frontend!'));
// My favourite language is <span>#javascript</span> because I love <span>#frontend</span>!
console.log(wrapHashtagsInText('Привет #user and #admin!!!'));
// Привет <span>#user</span> and <span>#admin</span>!!!