Har*_*iec 0 html javascript jquery function
我有一个<textarea id="mytextarea"></textarea>.
让我们说一个用户输入: <hello>, world!
如何res = "<hello>, world!";从用户输入的内容中获取?
此代码不起作用:
var res = $('#mytextarea').val().html();
Run Code Online (Sandbox Code Playgroud)
它说:
Uncaught TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)
PS var res = $('#mytextarea').val(); 工作正常,但我需要textarea的文本变成html转义.
如何用jQuery做到这一点?
谢谢.
已经回答:我可以在JavaScript中转义html特殊字符吗?
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
var res = escapeHtml($('#mytextarea').val());
Run Code Online (Sandbox Code Playgroud)
像这样的东西可以工作:
var res = $("<div/>").text($('#mytextarea').val()).html();
Run Code Online (Sandbox Code Playgroud)