简体   繁体   English

替换不工作?使用Javascript / jQuery的

[英]Replace not working?? Javascript/Jquery

I guess I'm too dumb for this. 我想我太愚蠢了。 Why my code only replace the first instance of each word? 为什么我的代码只替换每个单词的第一个实例? I want to highlight all words with those names 我想用这些名字突出显示所有单词

 //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> 

You'll have to use a regular expression with the 'g' flag if you want to replace all. 如果要替换all,则必须使用带有'g'标志的正则表达式。

See this little snippet: 看到这个小片段:

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

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

Use Regex, "OK" to /OK/g with global flag. 使用正则表达式,使用global标志"OK"/OK/g

 //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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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