I want to wrap every word of a string in a <span> tag, without breaking any existing html tags and without including any punctuation marks.
For example the following string:
This... is, an. example! <em>string</em>?!
should be wrapped as:
<span>This</span>... <span>is</span>, <span>an</span>. <span>example</span>!
<span><em>string</em></span>?!
Ideally, I just need to wrap the words and nothing else.
Except for apostrophes, they should be wrapped, too.
it's => <span>it's</span>
give 'em => <span>give</span> <span>'em</span>
teachers' => <span>teachers'</span>
Right now I’m using a very simple regular expression:
str.replace(/([^\s<>]+)(?:(?=\s)|$)/g, '<span>$1</span>');
I found it somewhere here on stackoverflow. But it only wraps every word on white spaces and wraps punctuation marks too, which is undesirable in my case.
I know I should be ashamed for being so lousy at regular expressions.
Can someone please help me?
Many thanks!
Try this regex: