我试图突出显示代码(并最终清理HTML),但我的正则表达式不仅仅匹配函数名称和参数。我不擅长正则表达式,有点让我很开心。此外,当我尝试在匹配结果上使用.replace()
来清理HTML并添加<pre>
括号时,它会给我错误Uncaught TypeError: undefined is not a function
我猜是因为它是因为它没有返回基本字符串?
var content = $('#content'),
html = content.html(),
result = html.replace(/\s.*\(.*\)\s/gi, "<pre>$&</pre>");
// When trying to add the <pre> tags in the last line of code
// And use this to sanitize my html.match() I get a error
// escapedRes = result.replace(/&/g, "&")
// .replace(/</g, "<")
// .replace(/>/g, ">")
// .replace(/"/g, """)
// .replace(/'/g, "'");
// Uncaught TypeError: undefined is not a function
content.html(result);
var content = $('#content'),
html = content.html(),
result = html.match(/\w+\(.+?\)/g);
var escapedRes = result.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/(/g, "(")
.replace(/)/g, ")")
.replace(/\*/g, "*")
.replace(/$/g, "$");
var result = escapedRes.replace(result, '<pre>'+escapedRes+'</pre>');
content.html(result);
答案 0 :(得分:3)
使用此正则表达式:
/\w+\(.+?\)/g
在您的消毒部分,您需要
result = html.match(/\w+\(.+?\)/g)[0];
as match()返回一个数组。
此外,您需要使用反斜杠转义(
和)
以及$
,因为它们在正则表达式中具有特殊含义。