Sathya Sathya - 1 year ago 69
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,

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

Html output,

<div class="accordion">
<div class="accordion-content">
content 1
<div class="accordion-content">
content 2

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download