简体   繁体   中英

Regex match javascript/php function name in str

I'm trying to highlight code (and eventually sanitize the HTML) but my regex is not matching just the function name and params. I am no good at regex, it kinda boggles me to begin with. Also when I try to use .replace() on my matched result to sanitize the HTML and add the <pre> brackets, it gives me the error Uncaught TypeError: undefined is not a function which I am guessing is because it's not returning a basic string?

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 Example

Broken 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 Example

Use this regex:

/\w+\(.+?\)/g

DEMO

Update:

On your sanitizing part, you need to do

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

as match() returns an array.

Also, you'll need to escape ( and ) and $ with backslash, as they have special meaning in regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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