How do I escape a string inside JavaScript code inside an onClick handler?

前端 未结 13 900
半阙折子戏
半阙折子戏 2020-11-28 03:44

Maybe I\'m just thinking about this too hard, but I\'m having a problem figuring out what escaping to use on a string in some JavaScript code inside a link\'s onClick handle

13条回答
  •  感情败类
    2020-11-28 04:15

    Depending on the server-side language, you could use one of these:

    .NET 4.0

    string result = System.Web.HttpUtility.JavaScriptStringEncode("jsString")
    

    Java

    import org.apache.commons.lang.StringEscapeUtils;
    ...
    
    String result = StringEscapeUtils.escapeJavaScript(jsString);
    

    Python

    import json
    result = json.dumps(jsString)
    

    PHP

    $result = strtr($jsString, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"', 
                                     "\r" => '\\r', "\n" => '\\n' ));
    

    Ruby on Rails

    <%= escape_javascript(jsString) %>
    

提交回复
热议问题