Javascript String.replace(/\\$/,str) works weirdly

2019-01-15 10:31发布

问题:

For simplicity, i have the following file named test.jsp:

<script language="javascript">
    alert("a$b".replace(/\$/g,"k"));
</script>

I put this file in my local server, then display it using firefox: http://localhost:8080/myproj/test.jsp. It works okay, the result alert string is:

 akb

But when i put this file in a remote server and use the same firefox to display, it output is: a$bk which is incorrect for me.

Then i change the test.jsp content to:

<script language="javascript">
    alert("a$b".replace(/\\$/g,"k"));
</script>

Note here i add two slashes instead of one. In this case it works in the remote server but not in local one.

Then i rename the file from test.jsp to test.html, but the content is the same as my first case, i.e.:

<script language="javascript">
    alert("a$b".replace(/\$/g,"k"));
</script>

By using the same firefox, it works okay in both servers.

But my file needs to embed the javascript in jsp file. it is not allowed to use .html suffix for my file. What should I do to write a portable javascript in this scenario?

My local server uses tomcat-5.5.26; remote server uses tomcat-5.0.28. Firefox version is 3.0.4.

回答1:

JSP 2.0 Spec says: "When EL evaluation is disabled, \$ will not be recognized as a quote, whereas when EL evaluation is enabled, \$ will be recognized as a quote for $." (JSP.3.3.2)

Whether EL Evaluation is enabled or disabled depends on many things:

  • if application server supports JSP 2.0 (Tomcat 5.0 and higher does)
  • web.xml descriptor file... if declares (e.g. by not using web-app_2_4.xsd schema) that it uses Servet 2.3 spec or earlier, EL is disabled by default.
  • JSP Configuration <el-ignored>
  • Page directive isELIgnored (<%@ page isELIgnored=”true|false” %>)

(See JSP Spec 2.0, part JSP.3.3.2 for more details)

Simple way to check if EL is enabled/disabled is to use ${request} on your page. If you see '${request}' in output, EL is disabled. If you see something different, it is enabled.

You may want to change \$ (one backslash) to \\$ (two backslashes) to get \$ in output if you also use EL on your page.

If you see differences between local/remote server, their settings related to EL probably differ. Best what you can do is to 1) use JSP 2.0, Servlet 2.4 or later (enables EL), 2) run same web server on machines. (Btw, I suggest you upgrade Tomcat 5.0 to 5.5 at least).



回答2:

Maybe you can move the javascript code to a separate .js file? This will prevent the code from being interpreted as jsp.



回答3:

Peter's got it, and Simon's suggestion is also a good idea.

Additionally, you don't need to use regex to do a simple static-string replace. The JS idiom would be:

alert('a$b'.split('$').join('k'));