Echo JavaScript Safely

I am working on the data validation side of my WordPress theme. I have an option where user can input JS in the backend, and same is outputted in the front end between the script tags.

The problem I am facing is, I am not able to find a WordPress function that allows only JavaScript to pass through. What if user types some junk, CSS/HTML in it?

Is there any function in WordPress core/PHP that I can use? Or will I have to just echo it straightaway?

Solutions Collecting From Web of "Echo JavaScript Safely"

What you’re asking for is impossible, there is no such thing as a safe javascript entry box.

Even if we strip out extra script and style tags, it’s pointless, as the javascript code itself is inherently dangerous, and can create any elements it wants using DOM construction, e.g.:

var s = jQuery( 'script', { 'src': '' } );
jQuery('body').append( s );


var s = jQuery( 'link', {
    'rel': 'stylesheet',
    'type': 'text/css',
    'href': ''
} );
jQuery('body').append( s );

Nevermind something that steals your login cookies, etc. Javascript is inherently dangerous, and what you’re trying to implement is an attack vector. This isn’t because people might break out of javascript, but because the javascript itself is potentially dangerous

From this answer:

If you want to allow the user to be able to input their own Javascript code, but you don’t want to allow them to enter any HTML, you could use something like this:

preg_match( '/\A<script((?!<[a-zA-Z])[\s\S])*</script>\Z/', trim($input) );

The trim function removes whitespace from the beginning and end, and the regex pattern will only match the string if it begins with '<script', ends with '</script>', and doesn’t have any '<' characters immediately followed by a letter. That should effectively keep any stray HTML out, while allowing the user to put some Javascript code using a less than operator, if they need to for some reason.

The other thing I would do is make sure that only an administrator can set this option, and if he or she sneaks some HTML into there and breaks their own website, it’s their own fault. Of course, if this is going into the database, make sure it is sanitized for SQL.

You should not let users enter JS code. Users are not developers and should not write code. Once a user writes code the responsibility of anything bad that might happen is on him, and there is very little you might or should do cause after all it is his site and if he wants to write code then who are you to tell him “no”.

Now, it is a very bad UX to force a user to enter JS code, so the question should be is there a better way to let user input the info without resorting to writing code (and unfortunately, not always there is one).