[英]Javascript - Replacing the escape character in a string literal
我正在嘗試替換 Javascript 字符串文字中的反斜杠(轉義)字符。
我需要用雙反斜杠替換它,以便我可以進行重定向:
var newpath = 'file:///C:\funstuff\buildtools\viewer.html'.replace(/\\/g,"\\");
window.location = newpath;
然而,似乎沒有結果。
在 Javascript 處理反斜杠之前,我沒有正確轉義反斜杠的選項。
我怎樣才能用 (\\) 替換 (\) 以便 Javascript 會很高興?
謝謝,德里克
如果它是文字,你需要在 Javascript 看到它們之前轉義反斜杠; 沒有辦法解決這個問題。
var newpath = 'file:///C:\\funstuff\\buildtools\\viewer.html';
window.location = newpath;
如果newpath
從其他地方獲取它的值,並且確實包含單個反斜杠,則不需要將它們加倍; 但是如果出於某種原因你真的想要這樣做,請不要忘記在 replace() 調用中轉義反斜杠:
newpath.replace(/\\/g,"\\\\");
為什么您不能選擇在 Javascript 處理反斜杠之前正確轉義反斜杠? 如果問題是您的 Javascript 源代碼是從其他一些本身使用 \ 作為轉義字符的腳本語言生成的,只需添加一個轉義級別:
var newpath = 'file:///C:\\\\funstuff\\\\buildtools\\\\viewer.html';
為了更好地演示和理解字符串轉義行為,請看以下示例:
通過拆分字符串,您可以看到字符串在被 JS 引擎解析后在內存中的樣子,因此也提供了解決此問題的潛在(丑陋)解決方案:
'file:///C:\funstuff\buildtools\viewer.html'.split('')
//>
["f", "i", "l", "e", ":", "/", "/", "/", "C", ":", "", "u", "n", "s", "t", "u",
"f", "f", "", "u", "i", "l", "d", "t", "o", "o", "l", "s", "", "i", "e", "w",
"e", "r", ".", "h", "t", "m", "l"]
'file:///C:\funstuff\buildtools\viewer.html'.split('').map( function(e){
return e.charCodeAt()
});
//>
[102, 105, 108, 101, 58, 47, 47, 47, 67, 58, 12, 117, 110, 115, 116, 117, 102,
102, 8, 117, 105, 108, 100, 116, 111, 111, 108, 115, 11, 105, 101, 119, 101,
114, 46, 104, 116, 109, 108]
//>in Hex values by applying .toString(16)
["66", "69", "6c", "65", "3a", "2f", "2f", "2f", "43", "3a", "c", "75", "6e",
"73", "74", "75", "66", "66", "8", "75", "69", "6c", "64", "74", "6f", "6f",
"6c", "73", "b", "69", "65", "77", "65", "72", "2e", "68", "74", "6d", "6c"]
基本上,單個反斜杠會轉義后面的字符,如果不注意轉義上下文,則會產生意想不到的結果。
解決方案:
通過查找表,您可以恢復許多錯誤轉義的字符,如果它們位於\x20-\x7F
的可打印 ASCII 字符范圍之外。 例如,對於上面的示例, 12
或\x0c
[ 12..toString(16)
] 將變為'\\'+'v'
,依此類推。
PS:請注意發生了信息丟失,並且您正在嘗試通過上下文或元信息恢復信息,這意味着在您的情況下該字符串在可打印的 ASCII 范圍內。
請與社區分享任何實施。 干杯!
您應該替換為“\\\\”,因為“\\”正在轉義為單個 \,因此沒有變化。
<< 轉義字符替換>>
import java.util.Scanner;
public class Example7 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentence: ");
String a=in.nextLine();
//System.out.println("the word had enter: "+a);
String Str1 = a.replace("\\n", "(new_line)");
//System.out.println(Str1);
String Str2 = Str1.replace("\\t", "(tab)");
//System.out.println(Str2);
String Str3 = Str2.replace("\\t", "(tab)");
String Str4 = Str3.replace("\\\\", "(comment_line)");
String Str5 = Str4.replace(":)", "(smile) ");
System.out.println("The new sentence:" +Str5);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.