Regex match javascript/php function name in str



我试图突出显示代码(并最终清除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, "&amp;")
    //           .replace(/</g, "&lt;")
    //           .replace(/>/g, "&gt;")
    //           .replace(/"/g, "&quot;")
    //           .replace(/'/g, "&#039;");
    // Uncaught TypeError: undefined is not a function 
content.html(result);

JSFiddle示例

破碎的Sanitize Fiddle

var content = $('#content'),
    html = content.html(),
    result = html.match(/w+(.+?)/g);
var escapedRes = result.replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;")
    .replace(/(/g, "&#40;")
    .replace(/)/g, "&#41;")
    .replace(/*/g, "&#42;")
    .replace(/$/g, "&#36;");
var result = escapedRes.replace(result, '<pre>'+escapedRes+'</pre>');
content.html(result);

JSFiddle示例

使用此正则表达式:

/w+(.+?)/g

演示

更新:

在你的消毒部分,你需要做

 result = html.match(/w+(.+?)/g)[0];

as match()返回一个数组。

此外,您还需要用反斜杠转义()$,因为它们在regex中具有特殊含义。

最新更新