h2O
h2O

Reputation: 544

Javascript lastIndexOf not working

I am trying to remove fakepath from a URL using lastindexof function in pure javascript But no output is being shown the following is my JS code :-

function myFunction()
{
var str="C:\fakepath\somefile.txt";
var m=str.lastIndexOf("\");
var n=str.substring(m+1);
document.getElementById("demo").innerHTML=n;
}

The following is my HTML code:-

<p id="demo">
    Click the button to locate where in the string a specified value occurs.
</p>
<button onclick="myFunction()">Try it</button>

You can find the working example at my jsfiddle at -> http://jsfiddle.net/xKPaK/4/

Upvotes: 2

Views: 9166

Answers (1)

zzzzBov
zzzzBov

Reputation: 179256

  1. \ characters must be escaped
    backslashes are used to create special characters in strings. For example, '\n' creates a string with a value of the newline character, while '\\n' creates a string with a value of \n.
  2. myFunction must be in global scope to be called in an HTML attribute callback.
    This is a quirk of jsfiddle. The contents of the JavaScript pane are actually executed within a function, which creates new scope for variables and functions. Simply adding the function to the global object will fix the issue.
function myFunction() {
    var str,
        m,
        n;
    str = "C:\\fakepath\\somefile.txt";
    m = str.lastIndexOf("\\");
    n = str.substring(m + 1);
    document.getElementById("demo").innerHTML = n;
}
window.myFunction = myFunction;

fiddle

Upvotes: 1

Related Questions