【问题标题】:Replace not working?? Javascript/Jquery更换无效?? Javascript/Jquery
【发布时间】:2018-08-21 16:00:59
【问题描述】:

我想我对此太愚蠢了。为什么我的代码只替换每个单词的第一个实例?我想突出显示所有具有这些名称的单词

//highlight words in the results
$("#results").html(function() {
  return $(this).html()
    .replace("OK", '<span class="label label-success p-3">OK</span>')
    .replace("ERROR:", '<span class="label label-danger p-3">ERROR:</span>')
    .replace("FAIL:", '<span class="label label-warning p-3">FAIL:</span>')
    .replace("AssertionError:", '<span class="label label-warning p-3">AssertionError:</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<span id="results" style="white-space: pre-line">Running test: fasf
.
----------------------------------------------------------------------
Ran 1 test in 0.652s

OK
FAIL:
ERROR:
Running test: test1
.
----------------------------------------------------------------------
Ran 1 test in 15.457s

OK
FAIL:
ERROR:
</span>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

使用正则表达式,"OK"/OK/gglobal 标志。

//highlight words in the results
    $("#results").html(function() {
        return $(this).html()
            .replace(/OK/g, '<span class="label label-success p-3">OK</span>')
            .replace(/ERROR/g, '<span class="label label-danger p-3">ERROR:</span>')
            .replace(/FAIL/g, '<span class="label label-warning p-3">FAIL:</span>')
            .replace(/AssertionError/g, '<span class="label label-warning p-3">AssertionError:</span>');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


<span id="results" style="white-space: pre-line">Running test: fasf
.
----------------------------------------------------------------------
Ran 1 test in 0.652s

OK
FAIL:
ERROR:
Running test: test1
.
----------------------------------------------------------------------
Ran 1 test in 15.457s

OK
FAIL:
ERROR:
</span>

【讨论】:

    【解决方案2】:

    如果要全部替换,则必须使用带有“g”标志的正则表达式。

    看看这个小sn-p:

    const theString = 'foo';
    
    console.log(theString.replace('o', 'i'))
    console.log(theString.replace(/o/g, 'i'))

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

    【讨论】:

      猜你喜欢
      • 2013-12-12
      • 2012-05-02
      • 1970-01-01
      • 2012-08-01
      • 2013-05-11
      • 2012-11-21
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      相关资源
      最近更新 更多