使用javascript搜索"\" [英] Searching for '\' using javascript
问题描述
我写了下面的代码来获取文件名,不带扩展名和路径.我正在浏览器中运行它.
I have written a following code to get just the file name without extension and path.I m running it in browser.
<script type="text/javascript">
var str=new String("C:\Documents and Settings\prajakta\Desktop\substr.html");
document.write(str);
var beg=str.lastIndexOf("\");// **HERE IS THE PROBLEM IT DOESNT GIVE ME THE INDEX OF '\'**
alert(beg);
var end=str.lastIndexOf (".");
alert(end);
document.write("<br>"+str.slice(beg+1,end));
</script>
,但是如果我用另一个字符ex.('p')替换'\',则可以使用相同的代码.我只是为ex初始化var str,但在我的应用程序中它并不总是固定的.由于我是Java的新手,任何机构都可以告诉我问题出在哪?怎么解决呢?
but the same code code works if i replace'\' by another character ex.('p'); i m initializing var str just for ex but in my application it is not always fixed.As i m new to Javascript can any body plz tell me what is the problem?n how to solve it?
推荐答案
您需要转义反斜杠字符.使用以下内容:
You need to escape your backslash character. Use the following:
var beg=str.lastIndexOf("\\");
是的,除非您也将原始字符串中的反斜杠转义了,否则它将给出-1:
Yes, it will give a -1 unless you escape the backslashes in your original string as well :)
使用此:
var str=new String("C:\\Documents and Settings\\prajakta\\Desktop\\substr.html");
反斜杠是Java的转义字符-这意味着反斜杠后面的字符是指特殊字符.因此,在您的原始字符串中,\ prajakta将被解释为"\ p" +"rajakta",其中"\ p"的含义非常不同.因此,您需要在每个字符串的任何地方都使用' \\
'.
Backslash is the Javascript escape character - this means that characters following a backslash refer to special characters. Thus, in your original string, \prajakta would be interpreted as '\p' + 'rajakta' where '\p' has a very different meaning. Thus, you need to use '\\
' everywhere in every string.
这篇关于使用javascript搜索"\"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!