1

I have this jQuery, and I would like to search for a string and replace it. I know with php I can use $0, $1, $2 etc. to get the matches.

This is how I would do this via php $0 in this example would be replaced with the found plater and keep it's upper/lower casing:

preg_replace("/plater/i", "<span class='plater'>$0</span>", $input);

How can I do this in javascript? When I try $0 it actually outputs $0 to the browser, and not what was found. Here is what I currently have:

$(document).ready(function(){
    var html = $("body").html();
    $("body").html(html.replace(/plater/ig, "<span class='plater'>$0</span>"));
});
4

3 回答 3

3

用括号捕获它并使用 $1 来指代“第一个”捕获组。

html.replace(/(plater)/ig, "<span class='plater'>$1</span>")

几种语言的正则表达式指南:http ://www.regular-expressions.info/javascript.html

于 2013-01-07T22:56:56.247 回答
2

要替换字符串:

html.replace(/(plater)/ig, '<span class="plater">$1</span>');

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

于 2013-01-07T22:56:20.293 回答
1

由于您只是在搜索“盘子”,因此您可以省去麻烦,只需plater在字符串中写入单词,但$&可用于引用整个匹配项。

于 2013-01-07T22:56:17.203 回答