Ben McCormick
Ben McCormick

Reputation: 25728

Regular Expression to surround whitespace with tags and replace it

I have some javascript that generates an html string, then passes it to some more javascript that I do not control, where all whitespace is collapsed (don't ask).

I would like to maintain my whitespace across this transformation, by changing the whitespace to a character (I've been using periods) and using a span to set the text color to be the same as the background. This text can't be highlighted, so this is a reasonably accurate whitespace substitute

I'm trying to develop a regex that will allow me to do a transformation like this

"a b c" -> `"a...b.c"

I know I can take care of the simple case by simply replacing every single space with the <span>.</span> like this str.replace(/s/g,"<span class="whitespace">.</span>) but I'd really prefer to remove the excess tags and match each group of whitespace instead of having an individual span tag for each space.

Any suggestions would be appreciated.

Upvotes: 0

Views: 380

Answers (3)

Joe
Joe

Reputation: 63424

How about this: three steps.

  1. Match all white space of 3 or more. Replace the 'inside' spaces.

    /(?<=\s)\s+(?=\s)/./

  2. Match all single white spaces not preceded by a period.

    /(?<!\.)\s/<span>./

  3. Match span followed by dots.

    /(<span>\.+)/$1<\/span>/

(My regex-fu is only brown belt so you might need to adjust for some escapes or such).

Upvotes: 0

Ben McCormick
Ben McCormick

Reputation: 25728

I was able to do it like this:

var str=name.replace(/\s+/g,'<span class="whitespace">$&</span>');
str=str.replace(/\s/g,".");
return str;

Upvotes: 2

inDream
inDream

Reputation: 1277

Have you tried convert all whitespace to &nbsp; ?

str.replace(/\s/g,'&nbsp;')

Upvotes: 0

Related Questions