Sathya Sathya - 1 month ago 17
React JSX Question

How to replace multiple occurrences of string in javascript?

I have created websites with reactjs. For restAPI's i used java and CMS is liferay. In liferay i had created the shortcode for accordion like

('[accordion][acc-header]Heading 1[/acc-header][acc-content]Content1[/acc-content][acc-header]Heading 2[/acc-header][acc-content]Content2[/acc-content][/accordion]')
.

I want to replace html elements instead of this strings. How to do in javascript?

Here you go,

[accordion]
[acc-header]Heading 1[/acc-header][acc-content]Content1[/acc-content]
[acc-header]Heading 2[/acc-header][acc-content]Content2[/acc-content]
[/accordion]


Html output,

<div class="accordion">
<h3>Heading1</h3>
<div class="accordion-content">
content 1
</div>
<h3>Heading2</h3>
<div class="accordion-content">
content 2
</div>
</div>

Answer

Dirty and quick way:

var s = '[accordion][acc-header]Heading 1[/acc-header][acc-content]Content1[/acc-content][acc-header]Heading 2[/acc-header][acc-content]Content2[/acc-content][/accordion]';
s.replace(/\[([a-z\-]+)]/g, '<div class="$1">').replace(/\[\/[a-z\-]*]/g, '</div>')

The result is:

"<div class="accordion"><div class="acc-header">Heading 1</div><div class="acc-content">Content1</div><div class="acc-header">Heading 2</div><div class="acc-content">Content2</div></div>"

This won't add <h3> tags