janhartmann
janhartmann

Reputation: 15003

Parts of string in bold text

I have a unordered list that contains

<ul id="strip">
     <li><a href="#"><span>This-is a test string</span></a></li>
    <li><a href="#"><span>This is without</span></a></li>
     <li><a href="#"><span>New-test</span></a></li>
</ul>

I need to bold the text before the "-", so in the first <li> "This" is bolded.

I'm stuck in the loop where I should find the "-".

NB: Regular JavaScript, no JQuery :-)

Upvotes: 1

Views: 8524

Answers (1)

Eldar Djafarov
Eldar Djafarov

Reputation: 24667

Use stringObject.replace(findstring,newstring) method.
In your case liString.replace(/\b(.*?-.*?)\b/,"<strong>$1</strong>")
full solution:

var lists = document.getElementsByTagName("li");
var listsL = lists.length;

for (var i = 0; i < listsL; ++i){
   liString = lists[i].innerHTML;
   liString = liString.replace(/\b([^-]*-[^\b]*?)\b/,"<strong>$1</strong>");
   lists[i].innerHTML = liString;
}

Upvotes: 5

Related Questions