简体   繁体   中英

How to pass a string that contains single and double quotes?

I have string variable called name . name contains the string 14'6" . I'm trying to pass name to a function. I'm trying to add an onclick to a tablerow this like this:

$("#trID").attr('onclick', 'testFunction(' + name + ')');

I tried using the escape character to achieve this, however I didn't get this to work because the string contains both a single quote ( ' ) and a double quote ( " ).

Is there a way I can pass thing string in to a function or do I have to change the string completely?

Thanks!

To do what you require you need to escape the single/double quotes within the name string. To do that you could use a regex:

name = name.replace(/([\""|\''])/g, '\\$1');
$("#trID").attr('onclick', 'testFunction(' + name + ')');

However it should be noted that using inline event handlers, ie. the onclick attribute in your example, is not good practice. You should use unobtrusive event handlers instead.

As you've already included jQuery in the page it would be achieved with an event handler and a data attribute, like this:

 let $div = $("#trID").on('click', function() { console.log($(this).data('foo')); }); $('button').on('click', function() { $div.data('foo', (new Date()).getTime()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="trID" data-foo="14'6"">Click me to display value</div> <button>Click me to change value</button>

Try the string template of javascript

$("#trID").attr('onclick', `testFunction(${name})`);

You can use JSON as proxy since its array syntax is based on JavaScript and JSON.stringify() can cope with JSON fragments (such a standalone string):

 function testFunction(param){ console.log(param); } var rawName = "one\n\"two\"\n'three'\nfour"; var encodedName = JSON.stringify(rawName); console.log(rawName, encodedName); $("#trID").attr('onclick', 'testFunction(' + encodedName + ')');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="trID">Click Me!</button>

It's worth noting anyway that you don't need it in the first place. Dynamically generated code is hard. Since you're using jQuery, a cleaner way would be:

 function testFunction(param){ console.log(param); } var name = "one\n\"two\"\n'three'\nfour"; $("#trID").on('click', function() { testFunction(name); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="trID">Click Me!</button>

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