Posted on April 23, 2015 in HTML/CSS Category with Normal Difficulty
When editing someone's html code can be a real pain, because they contain all kind of classes, ids or other attributes and you want them removed, just to have a clean markup to work with elements easily.
So, in this tutorial I will teach you how to find and replace regex html tag or attribute using your favorite code editor that has find and replace with regular expression feature (very simple and handy).
In Sublime Text or any other code editor you can use regular expressions to get rid of unwanted tags, classes and even attributes. Just open the search bar (CTRL+F), make sure to select the icon with a dot and asterisk (.*) which means "Enable Regular Expressions", then you can find and replace regex html tag or attribute.
In the picture below we have a useless attribute onclick which we want it removed in all <a> anchor tags, or you can remove them globally. The same you can do with classes or ids, if your html tag have it.`
You just need to write the attribute and add the regex code .+? which means anything. You can find more examples below. Just click on Find All button and then delete your selection.
To delete all html tags and leave only the text inside tags you can use the same regular expression as above, but only with surrounded with greater and lower characters. As you can see in the image below only what is inside the html tag it remains there.
To delete only a certain tag just add the same code as above, but only with li, div, img, table or whatever element you want, after the lower sign. Here is an example in Notepad++ this time.
The second example with asterisk means the selection goes
To remove only the <li> tag within his end </li>, but not deleting anything inside, use the .? regular expression. Unlike the regex above, this one searches until reaches the end of the line, and is not matching the exact target as the other one.
If you want to read more about regular expressions, I recommend you to read carefully this article on Wikipedia. It will help you understand all the terms and operators.
This trick might help you when you want to clean some html code and delete unnecessary things such as classes, ids or any other annoying attribute and leave a nested and simple code.