开发者

Converting Escaped Literals to Specials with JavaScript

I want to have a text input which users are able to enter special characters such as \n. 开发者_开发技巧However when I try to get the value inside the input I get the escaped string. I need to unescape the value or any workarounds?

EDIT: I put an example http://jsfiddle.net/9hmHr/


Do you mean this?

<textarea id="x">hello\ndolly</textarea>
<button onclick="alert(document.getElementById('x').value.replace(/\\n/g,'\n'))">Click</button>

Demo forked from your code

var str = 'aaasddd';

alert(
  str.replace('s', 
    $('#my').val().replace(/\\n/g,'\n')
  )
);


I found an interesting way to do this after searching a while for a more well-rounded solution, that didn't involve replacing every character with its literal form.

var x = "\\thello\\n\\tworld",
    y = JSON.parse(
        JSON.stringify(x).replace(/\\\\/g,'\\')
    );

console.log("Original:");
console.log(x);

console.log("Literal:");
console.log(y);

The above outputs:

Original:
\thello\n\tworld

Literal:
    hello
    world

I hope this helps!

NOTE: This may not work with strings that may contain braces ({ or }) as it may attempt to convert it into an object literal. You may be able to avoid this by "padding" the braces' escape characters. (e.g. changing "\{" to "\\\{")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜