Thinking80s
Thinking80s

Reputation: 2870

JavaScript replace string

regexp: var s = document.getElementById("username").value; if s == "\ \ \ \"; var result = s.replace(/\/g,"") will be wrong? why that firebug error ?

hope to the result is equals == "", but firebug is output:

SyntaxError { source="with(_FirebugCommandLine){("\ \").replace(/(\)/g,"");\n};", message="unterminated string literal", fileName="resource://firebug_rjs/console/commandLineExposed.js", more...}

why that? please help me?

Upvotes: 0

Views: 683

Answers (4)

fadzzz
fadzzz

Reputation: 11

\ symbol is regular expression...

\n = newline;
\t = tabspace;
\\ = "\" symbol;

so if you write // its will be mark as comment.... if you write \/ = "/" string.. but now you write "....replace(/\/gi)"...\/=/ will mark as string, so next word cannot close.. you must

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

the \\ meaning \ ...

Upvotes: 0

Guffa
Guffa

Reputation: 700342

Because you haven't escaped the backslashes in the string.

The backslash before the ending quote means that the quote is part of the string instead, so the string doesn't end until the next quote, so your code contains:

  • (
  • a string with the content ").replace(/(\\)/g,
  • a string with the content ); that is missing the ending quote

Escape the backslashes by doubling them:

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

Upvotes: 0

DhruvPathak
DhruvPathak

Reputation: 43235

you need to escape the backslash :

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

Upvotes: 0

Nivas
Nivas

Reputation: 18334

\ \ is a special character. See Special Characters in Javascript.

You have to escape \.

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

Should work.

BTW, what are you trying to do in your regEx match?

Upvotes: 2

Related Questions