2011-03-22 70 views

回答

1

你的意思呢?

<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') 
) 
); 
+0

我編輯了我的問題並按照您的意願放置了一個示例,謝謝。 – Ozgur 2011-03-22 21:49:58

+0

請參閱更新 – mplungjan 2013-05-22 04:52:03

0

我發現了一個有趣的方式,搜索一會兒一個更全面的解決方案,不涉及其字面形式替換每個字符之後做到這一點。

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); 

以上輸出:

Original: 
\thello\n\tworld 

Literal: 
    hello 
    world 

我希望這有助於!

注意:這可能不與可能包含括號({}),因爲它可能會嘗試將其轉換成一個對象文字字符串工作。您可以通過「填充」大括號的轉義字符來避免這種情況。 (例如,將"\{"更改爲"\\\{"