Charnstyle
Charnstyle

Reputation: 93

Use RegExp in JS to replace any html tags which include only whitespaces inside of it with its whitespaces(in same amount)

I would like to use RegExp in JS to replace any html tags which only include whitespaces(' ' or  ) inside of it with its html encoded equivalent  .

For example:

Replace

'<strong> &nbsp; &nbsp; </strong>' => '&nbsp; &nbsp;'

Another example,

Replace:

'<strong>&nbsp; &nbsp; &nbsp;</strong> => '&nbsp; &nbsp; &nbsp;'

Upvotes: 2

Views: 54

Answers (2)

GramThanos
GramThanos

Reputation: 3622

Lets say you have the string

var string = "<strong>&nbsp; &nbsp; &nbsp; </strong> <strong>no</strong>";

To match the only the spaces and the &nbsp; you can use

var result = string.replace(/<[^>]+>((&nbsp;| )+)<\/[^>]+>/gm, "$1");

Let me explain, <[^>]+> matches any tag and <\/[^>]+> any end tag. the (&nbsp;| )+ matches an space or an   many times

Upvotes: 0

Guffa
Guffa

Reputation: 700432

You can use a regular expression like this:

str = str.replace(/<(\w+)>((?:&nbsp;|\s)+)<\/\1>/g, '$2');

Explanation:

<(\w+)>          matches the start tag and captures the name
(                group to capture the content
(?:&nbsp;|\s)+   matches &nbsp; or whitespace, one or more times
)                ends group
<\/\1>           matches the end tag with the name of the start tag

The match is replaced by $2, i.e. the value in the second group, i.e. the content inside the tag.

Upvotes: 3

Related Questions