stillenat
stillenat

Reputation: 943

Regular expression for wrapping every word in span tag on word boundaries in javascript

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!

Upvotes: 1

Views: 2968

Answers (2)

Cerbrus
Cerbrus

Reputation: 72857

Try this regex:

var str = "This string... it's, an. example! <em>string</em>?!";
str.replace(/([A-Za-z0-9'<>/]+)/g, '<span>$1</span>');

// "<span>This</span> <span>string</span>... <span>it's</span>, <span>an</span>. <span>example</span>! <span><em>string</em></span>?!"

Upvotes: 4

Amir
Amir

Reputation: 2480

I played around and got this to work :

String toMarkUp = "Each word needs a strong tag around it.  I really want to wrap each and every word";

String markedUp = toMarkUp.replaceAll("\\b(\\w+)\\b","<span>$1</span>");

The regex is capturing every word with 1 or more characters (\w+) surrounded by word boundaries, and using forward lookup group to reference it in the replacement with a $1, 1 being the first capture group in the regex.

Output :

<span>Each</span> <span>word</span> <span>needs</span> <span>a</span> <span>strong</span> <span>tag</span> <span>around</span> <span>it</span>.  <span>I</span> <span>really</span> <span>want</span> <span>to</span> <span>emphasize</span> <span>each</span> <span>and</span> <span>every</span> <span>word</span>

Upvotes: 1

Related Questions