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
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);
5
Answers
You can use the
split()
function to separate the string into an array of words and then usemap()
to create a new array with each word wrapped in<div>
tags.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:If you want to retain your style of code, then replace this line:
with
Reasons:
text.replace(..)
call. This will make the code itself the text.text
. Hence, replace it withstr
, your actual variable.replace(..)
will replace only the first instance. You needreplaceAll(..)
for replacing all-
s.You can add the below tag in to your HTML page so it will work same as the above PHP.
It splits the input text into an array of words using the split method and then iterates through the array, writing each word surrounded by and tags to the document
Below javascript code will work perfectly