Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to properly replace hyphen with div elements in javascript

I have the following text stackoverflow-is-the-best-site-in-the-world by hyphen. I need to replace those hyphen and surround each text within div tags as per result sample below

<div class='cssx'>stackoverflow</div>
<div class='cssx'>is</div>
<div class='cssx'>the</div>
<div class='cssx'>best</div>
<div class='cssx'>in</div>
<div class='cssx'>the</div>
<div class='cssx'>world</div>

In PHP I can get it working as follow.

<?php
$str ="stackoverflow-is-the-best-site-in-the-world";
echo $output = str_replace('-', "<div class='cssx'></div>", $str);

?>

Here is my issue. I need to get it working with javascript. To this effect, I have leveraged solution here
source

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but cannot get it to work.

here is the code so far.

const str ="stackoverflow-is-the-best-site-in-the-world";

var output = "<div class='cssx'>" + 
"text.replace(/-/g, "</div><div class='cssx'>", str)" +
 "</div>";

alert(output);

>Solution :

Your code only needs a small fix. You should call the replace method on the str variable instead of using it as a string. Something like:

const str = "stackoverflow-is-the-best-site-in-the-world";

const output = "<div class='cssx'>" +
  str.replace(/-/g, "</div><div class='cssx'>") +
  "</div>";

alert(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading