I have the following string:
<h1 class="title">This is some heading?</h1><h2 class="desc">Here is the description for it.</h2>
Want to make it look like:
<h1 class="title">This is some heading? </h1> <h2 class="desc">Here is the description for it.</h2>
There are 2 parts in the above:
- Insert space after every special character. So in the above example, instead of question mark, it could be ! or & or ( or ) or % etc. and I need to insert space after such special characters.
- Remove all opening html tags & replace closing html tag with space.
For 1, I tried this:
str = str.replace(/\?/g,'? ');
The above does insert space after ? but it is very rigid. I can’t apply the same rule to all special characters. So how to do it?
For 2, I tried this:
//To entirely remove all opening html tags
str = str.replace(/<.*?>/g, '');
//To replace closing tag with space
str = str.replace(/<\/.*?>/g, ' ');
The problem with the code above is the later part works well. The first part, i.e. the code to remove all opening html tags also affects the closing html tags, which is undesirable. So how to modify above code so that opening tags, such as <h1>, <div>, etc. are removed?
For the first problem you could use:
For opening tag problem, you could use:
Basically,
[abcdef]means that its a placeholder for any of a,b,c,d,e,f. Similar for%and?. Putting a^within the class (the square bracket) means that its a placeholder for any character other than those that follow^. So<[^/]would not accept</string.