简体   繁体   中英

How do I target the second character with jQuery

I am using jQuery to target hyphens in word combinations in order to apply special styling.

The words are part of a filtering system and appear like this:

<ul id="filters" >
<li class="current"><a href="#all">All-Work</a>
<ul>
<li><a class="filterName" href="#Branding-and-Logo">Branding-and-Logo</a></li>
<li><a class="filterName" href="#Content-Management">Content-Management</a></li>
<li><a class="filterName" href="#Infographics">Infographics</a></li>
<li><a class="filterName" href="#Media-Integration">Media-Integration</a></li>
<li><a class="filterName" href="#Mobile-sites">Mobile-sites</a></li>
<li><a class="filterName" href="#Photography">Photography</a></li>
<li><a class="filterName" href="#Print">Print</a></li>
<li><a class="filterName" href="#Video">Video</a></li>
<li><a class="filterName" href="#Websites">Websites</a></li>
</ul>
</li>
</ul>

I am using the following jQuery to target the hyphen between words:

$('a:contains("-")').html(function () {
return $(this).text().replace('-', '<span class="hideme">-</span>')
});

This works on all instances except the first item in the list: Branding-and-Logo, where the second hyphen is not modified. You can see how the second hyphen still shows in the lists here .

What else needs to be done to target the second hyphen as well as the first?

当我需要替换字符串的所有实例时,我通常使用splitjoin

return $(this).text().split('-').join('<span class="hideme">-</span>')

.replace only replace the first instance passed in argument. You could call replace until there is no more hyphen, use dave's answer (which is good) or use regExp global flag like that :

return $(this).text().replace(/-/g, '<span class="hideme">-</span>');

Javascript replace function only replaces the first occurrence of the pattern. To replace all you must use a regular expression such as:

$('a:contains("-")').html(function () {
    return $(this).text().replace(/-/g, '<span class="hideme">-</span>')
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM