Passing a parameter to function with single quote

前端 未结 5 1068
抹茶落季
抹茶落季 2021-01-07 19:08

How do I pass a parameter to a javascript function with \' included

var name =\"Lauren O\'Donald\";

var htmlAnch=\'

        
5条回答
  •  悲哀的现实
    2021-01-07 20:12

    You can escape quotes/characters by prepending \ to it:

    var string = 'my string with "double quotes" and \'single quotes\'';
    var string = "my string with 'single quotes' and \"double quotes\"";
    //                                               ^              ^
    

    Using a dynamic string:

    var foo = "bar with 'quotes'";
    var string = 'my string with "double quotes" and ' + foo.replace(/'/g, "\\'");
    //my string with "double quotes" and bar with \'quotes\'
    

提交回复
热议问题