0

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks, that's part of the problem.
@WASasquatch, what is the other part?
It's in my question. I updated code to show problematic code. Which is based on using a match() in result insidead of replace
Please re-read my comment and question. This is based on the html.match(/\w+\(.+?\)/g) code as the <pre> is added afterwards.
@WASasquatch, .maatch() will only give you the matched part which is function(){ ... }. Why are you using that?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.