Reputation: 93
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> </strong>' => ' '
Another example,
Replace:
'<strong> </strong> => ' '
Upvotes: 2
Views: 54
Reputation: 3622
Lets say you have the string
var string = "<strong> </strong> <strong>no</strong>";
To match the only the spaces
and the
you can use
var result = string.replace(/<[^>]+>(( | )+)<\/[^>]+>/gm, "$1");
Let me explain, <[^>]+>
matches any tag and <\/[^>]+>
any end tag.
the ( | )+
matches an space or an many times
Upvotes: 0
Reputation: 700432
You can use a regular expression like this:
str = str.replace(/<(\w+)>((?: |\s)+)<\/\1>/g, '$2');
Explanation:
<(\w+)> matches the start tag and captures the name
( group to capture the content
(?: |\s)+ matches 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