JavaScript替换字符串

JavaScript替换字符串,javascript,regex,Javascript,Regex,regexp: var s=document.getElementById(“用户名”).value;如果s==“\\\”;var result=s.replace(/\/g,“”)是否错误?为什么会出现firebug错误 希望结果为equals==“”,但firebug是输出的: 语法错误{source=“with(\u FirebugCommandLine){(“\\”)。替换(/(\)/g,”;\n};”,message=“unterminated string literal”,file

regexp: var s=document.getElementById(“用户名”).value;如果s==“\\\”;var result=s.replace(/\/g,“”)是否错误?为什么会出现firebug错误

希望结果为equals==“”,但firebug是输出的:

语法错误{source=“with(\u FirebugCommandLine){(“\\”)。替换(/(\)/g,”;\n};”,message=“unterminated string literal”,fileName=”resource://firebug_rjs/console/commandLineExposed.js“,更多…”


为什么?请帮帮我?

\\是一个特殊字符

您必须退出
\

("\\ \\").replace(/(\\)/g,"");
应该有用


顺便说一句,你想在正则表达式匹配中做什么?

你需要避开反斜杠:

t = ("\\\\").replace(/(\\)/g,"");

因为你没有逃过字符串中的反斜杠

结束引号前的反斜杠表示引号是字符串的一部分,因此字符串直到下一个引号才结束,因此代码包含:

  • 内容为“
    ”)的字符串。替换(/(\\)/g,
  • 内容为
    );
    且缺少结尾引号的字符串
通过将反斜杠加倍来避免反斜杠:

("\\ \\").replace(/(\\)/g,"");

\符号是正则表达式

\n = newline;
\t = tabspace;
\\ = "\" symbol;
因此,如果你写//它将被标记为注释。。。。 如果您写入
\/=“/”
字符串。。 但现在您编写“…替换(/
\/gi)
”…
\/=/
将标记为字符串,因此下一个单词无法关闭..您必须

var s = document.getElementById("username").value; 
if(s.search("\ \ \ \")>=0){
   s.replace(/\\/g,"");
}

\\means\…

@kevin Peng,你想实现什么目标?