简体   繁体   中英

JavaScript/jQuery: Insert space after special characters and closing html tags

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:

  1. 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.
  2. 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, ie 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?

Match :

\s*(?<ws>[<>])\s*

and replace with

$1

For the first problem you could use:

s.replace(/([?%])/g, '$1 ') //you could put more characters within `[..]`

For opening tag problem, you could use:

str.replace(/<[^/].*?>/g, '')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM