使用正则表达式替换HTML - jQuery

时间:2015-06-28 19:46:14

标签: javascript jquery html css

我正在使用CMS制作网站。我的客户希望某些字符(如反斜杠和引号)与段落的其余部分具有不同的颜色,因此为了方便他,我想找到它们并用正确的内联样式替换它们。我的代码都是单独工作的,但我不能让它一起运行。只有脚本中的最后一个操作似乎正在执行(workContentCloseQuote)。

https://jsfiddle.net/n654kvdp/4/

$('.right-entry p').each(function() {
    var workContentBackslash = $(this).text();
    var workContentOpenQuote = $(this).text();
    var workContentCloseQuote = $(this).text();

    workContentBackslash = workContentBackslash.replace(/\//g, "<span style='color: red;'>/</span>");
    workContentOpenQuote = workContentOpenQuote.replace(/“/g, "<span style='color: red;'>“</span>");
    workContentCloseQuote = workContentCloseQuote.replace(/”/g, "<span style='color: red;'>”</span>");

    $(this).html(workContentBackslash);
    $(this).html(workContentOpenQuote);
    $(this).html(workContentCloseQuote);
});

<div class="right-entry">
    <header class="entry-header">
        <h1 class="entry-title">OKO</h1>
    </header>
    <div class="spacer">-</div>
    <p>branding / posters / responsive website / stationery / marketing / infographics</p>
    <p>Jeremy asked me to re-brand his company after I designed a set of book covers for him. I created a fresh new logo, colour ways and brand guidlelines along with a shiny new responsive site, posh stationery, office posters, twitter theme, etc. Visit the site oko.agency</p>
    <p>“Intuitive, intelligent and attractive design from an innovative creative. Simon takes the time to understand the brand, the business challenge and then delivers a creative solution within budget and timescale. What more could you ask for”.</p>
    <p>Jeremy Rix</p>
</div>

3 个答案:

答案 0 :(得分:2)

您将使用以下更改覆盖每个更改。试试这个:

$('.right-entry p').each(function() {
    var text = $(this).text();

    text = text.replace(/\//g, "<span style='color: red;'>/</span>");
    text = text.replace(/“/g, "<span style='color: red;'>“</span>");
    text = text.replace(/”/g, "<span style='color: red;'>”</span>");

    $(this).html(text);
});

此外,您可以使用一个表达式替换整组字符:

text = text.replace(/[\/“”]/g, "<span style='color: red;'>/</span>");

答案 1 :(得分:2)

html方法重置元素的html内容。您应该链接replace个调用并修改相同的字符串。您还可以使用html方法的回调函数:

$('.right-entry p').html(function(_, currentHTML) {
   return currentHTML.replace(/([\/“”])/g, "<span class='red'>$1</span>");
});

https://jsfiddle.net/yxL9okot/

答案 2 :(得分:1)

如果您使用.html(),它将替换您定位的任何元素的内容。在您的情况下,它可以简化为以下内容:

$('.right-entry p').each(function() {
    this.innerHTML = this.innerHTML.replace(/([\/“”])/g, "<span style='color: red;'>$1</span>");
});