# Converting Confluence markup to a simpler XML format

I have a code that converts one xml structure to another. I am removing unnecessary tags and replacing some temporarily. I think I have way too many replace operations and wondering if there is a way to optimize this. Can someone pour in suggestions?

Note: I am not using regex to convert xml to plain text. All I am doing using regex is to do away with certain unwanted tags not supported by target xml format, and temporarily replace a few inline elements and replace them back after converting (so that I dont need to parse the inline elements). After sanitizing the string, I am parsing it using jquery xml parser.

Here's the code snippet:

  str = str.replace(/\r?\n|\r/g, ''); //Remove all new line characters
// Replace <strong> tags to retain and convert them in the end
str = str.replace(/<strong>/g, '(strong)');
str = str.replace(/<\/strong>/g, '(/strong)'); //
// Replace <code> tags to retain and convert them in the end
str = str.replace(/<code>/g, '(code)');
str = str.replace(/<\/code>/g, '(/code)');
// Remove these tags as they arent required
str = str.replace(/<ac:rich-text-body>/g, '');
str = str.replace(/<\/ac:rich-text-body>/g, '');
// Remove 'ac:' from macros elements
str = str.replace(/ac:/g, '');
str = str.replace(/<\/*span.*?>/g, ''); //Remove all span tags
str = str.replace(/<\/*div.*?>/g, ''); //Remove all div tags
str = str.replace(/<br.*?>/g, ''); //Remove br tags
str = str.replace(/&nbsp;/g, ''); //Remove non-breaking white spaces
str = str.replace(/<\/*a.*?>/g, ''); //Remove a tags
str = str.replace(/<\/*u>/g, ''); //Remove u tags
str = str.replace(/<\/*em>/g, ''); //Remove em tags

• Could you provide more context about why you want to perform these transformations? Jun 13, 2017 at 20:55
• Replace multiple strings with multiple other strings Jun 14, 2017 at 10:22
• This doesn't look like converting markup to simpler XML but rather like removing markup and converting it to plain text. Jun 14, 2017 at 16:39
• Okay, I released now that using regex in xml parsing is a huge debate, and a sensitive area! I have put up a clarification and updated my question to avoid the confusion. Jun 15, 2017 at 5:48

• Yes, the cited question is more of a rant than an explanation. But code that does str.replace(/<ac:rich-text-body>/g, '') is indeed trying to parse XML/HTML using regular expressions, and it will fail for the reasons cited in that post: (a) XML is not a regular language in the computer-science sense of the term, and (b) more practically, you code depends on accidental and non-reliable properties of the input, such as the choice of namespace prefixes, the absence of whitespace in places where it is allowed, etc. Using a proper XML parser will avoid these problems. Jun 14, 2017 at 8:24