[英]How do I properly escape double-quotes when sending HTML from Applescript into Javascript?
[英]How can I escape double quotes from a text input in javascript?
在變量中,字符串數據來自文本輸入,如下所示。
var noteStr="<?php echo $_REQUEST["noteStr"];?>";
如果用戶在文本輸入中給了任何雙引號,那么javascript會給出預期的錯誤。 我沒有找到在這種情況下使用javascript str.replace()的方法,因為在對字符串變量javascript引擎使用它之前會生成錯誤。
如何使用JavaScript解決此問題? 預先感謝您的幫助。
使用PHP函數htmlspecialchars() 。
var noteStr="<?php echo htmlspecialchars($_REQUEST["noteStr"]); ?>";
這是等效的JavaScript:
function escapeHtml(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
Javascript中有一個很棒的內置函數。 escape()函數。
<script>
document.write(escape("Hello friends? Here is the solution!"));
</script>
會變成-
Hello%20friends%3F%20Here%20is%20the%20solution%21
退房-http ://www.w3schools.com/jsref/tryit.asp? filename = tryjsref_escape以供參考
這也可以通過在Javascript中使用原型來實現。 一個簡單的例子-
var str = '<div class="article">This is an article</div>';
document.write( str.escapeHTML() );
會變成-
<div class="article">This is an article</div>
來源: http : //www.tutorialspoint.com/cgi-bin/practice.cgi? file= prototype_83
希望能幫助到你! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.