Searching for '\' with javascript
I wrote the following code to get just the filename without extension and path. I am running it in a 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 works if I replace '\' with another ex character. ('p'); im initializing var str for ex only, but in my application it is not always fixed. How can I add any body plz to Javascript, 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("\\");
EDIT: Yes, it will give -1 unless you avoid backslashes in the original string :)
Use this:
var str=new String("C:\\Documents and Settings\\prajakta\\Desktop\\substr.html");
The backslash is a Javascript escape character - this means that characters following the backslash are special characters. So in your original line \ prajakta will be interpreted as '\ p' + 'rajakta', where '\ p' has a very different meaning. Thus, you need to use ' \\
' everywhere on every line.
source to share
"\"
is an escape character, try "\\"
Anyway, I would do it with regexes, just because I like them :)
var str=new String("C:\\Documents and Settings\\prajakta\\Desktop\\substr.html");
document.write(str);
document.write("<br>"+str.replace(/^.*\\/,"").replace(/\..*?$/,""));
Oh, and in testing I've seen that you also need to avoid backslashes in your test string!
source to share
The backslash is usually an escape character, so you'll have to type it twice when it happens on a string, i.e. your
var str=new String("C:\Documents and Settings\prajakta\Desktop\substr.html");
must read
var str=new String("C:\\Documents and Settings\\prajakta\\Desktop\\substr.html");
The point is that it is \D
interpreted by the javascript engine and will be replaced with the corresponding special character (in this case I don't believe there is a special character \D
(or 'p' or 's'), so it will be replaced simply D
and your string content will be
"C:Documents and SettingsprajaktaDesktopsubstr.html"
Go ahead, check it out with a simple
if (str == "C:Documents and SettingsprajaktaDesktopsubstr.html") alert("Doh! :)");
he should give you a warning.
Also, your
var beg=str.lastIndexOf("\");
must read
var beg=str.lastIndexOf("\\");
NTN.
source to share