conor909
conor909

Reputation: 1623

Properly escape characters in input value in JavaScript

My goal is to display Sarah O'Connor in an input as the value. I need to escape Sarah O' Connor to show the correct UTF-8 html character.

I'v seen some answers that suggest replacing each individual special character. But surely that's not the correct way as there could be hundreds of possible characters in peoples names from around the world.

I'v also tried javascripts escape() / unescape() and encodeURI() / decodeURI() functions, but they work only as html text not as input values.

Please see the jsFiddle here: http://jsfiddle.net/gHHzA/

var div = $("#my-div");
var input = $("input");
var str = "Sarah O'Connor";

div.html(str);   //--> Sarah O'Connor
input.val(str);  //--> Sarah O'Connor

Upvotes: 1

Views: 2455

Answers (1)

You can create an element to put the HTML, then you can get the formatted result with .text(), eg:

input.val($("<div>", {html:"Sarah O&#39;Connor"}).text())

Upvotes: 2

Related Questions