Hey folks, I’ve been wondering if there’s a neat trick to wrap text with HTML tags or other characters in JavaScript. You know, without resorting to the old-school string concatenation.
I know it might sound silly, but hear me out. There are already some cool functions for similar stuff, like trim() for removing whitespace, or split() and join() for working with arrays. Even some old HTML-related methods exist, though they’re not used much these days.
What I’m after is something like this:
let coolText = rawText.wrapWith('<p>', '</p>');
let quotedWords = phrase.wrapEachWord('"');
Instead of the more verbose:
let coolText = '<p>' + rawText + '</p>';
let quotedWords = phrase.split(' ').map(word => '"' + word + '"').join(' ');
Am I dreaming too big here? Or is there actually a slick way to do this that I’m missing? Would love to hear your thoughts!
hey mia92, i feel ya on wanting a smoother way to wrap text. sadly, js doesn’t have a built-in method for that exact thing. but you could make ur own function! something like:
function wrapText(text, wrapper) {
return ${wrapper}${text}${wrapper};
}
might do the trick for ya. not perfect, but it’s somethin!
While JavaScript doesn’t offer a native method for text wrapping, you can create a simple utility function to achieve this. Here’s an approach I’ve found effective:
function wrap(text, prefix, suffix = prefix) {
return ${prefix}${text}${suffix};
}
This allows for flexible usage:
let paragraphText = wrap(‘Your content here’, ‘
’, ‘
’);
let quotedText = wrap(‘Important quote’, ‘"’);
These functions offer a clean, reusable solution without modifying prototypes or relying on external libraries. They’ve simplified my code significantly in various projects.
I’ve actually been in your shoes before, Mia. While JavaScript doesn’t have a built-in method for this, I found a pretty neat workaround using prototype extension. Here’s what I did:
String.prototype.wrapWith = function(before, after) {
return before + this + (after || before);
};
This lets you do something like ‘Hello’.wrapWith(‘
’, ‘
’) or even ‘World’.wrapWith(‘*’) for symmetrical wrapping. It’s not perfect and some devs might frown upon extending prototypes, but it’s served me well in personal projects.
For wrapping each word, you could create a similar method: