Searching for '\' using javascript

javascript

Solution

You need to escape your backslash character. Use the following:

var beg=str.lastIndexOf("\\");

EDIT: Yes, it will give a -1 unless you escape the backslashes in your original string as well :)

Use this:

var str=new String("C:\\Documents and Settings\\prajakta\\Desktop\\substr.html");

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.

Problem

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> ``` 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?

Original source