0

I have a string called myStr="file://test"; I want to get text after file:// test out of it; I could do it with

myStr ="file://test"
myStr.substr(myStr.lastIndexOf('/') + 1);

but thats not the right way; could you please help me with regular expression: My attempt with regualr expression is the following, but it just checks (if exists it returns 0) whether it exists or not(if it does not exist -1 to return)

    myStr.search(new RegExp("file://"))

1 Answers1

0

Something like this should do it:

var myStr ="file://test";
var myStr2 = "asddfh";

function check(s) {
  var ret = s.match(/file\:\/\/(.*)/);
  return (ret && ret[1]) || -1;
}

alert(check(myStr));
alert(check(myStr2));

Returns everything after file:// or -1 if the file part is not found.

Two notes:

  • this only checks the browser URL, not if a file exists or similar
  • URLs for files have three slashes instead of two (file:///filenameHere)
Shomz
  • 37,421
  • 4
  • 57
  • 85
  • file://test is a string I'm working with in the code; it is not actual file! so s.match(/file\:\/\/(.*)/)[1] shoudl be fine I guess, right? –  Dec 23 '14 at 18:12
  • It will throw an error if `file://` is not found. That's why I wrote that fancy return statement - you need to check whether it's null first. If you need just 0 and -1, you can do: `s.search(/file\:\/\/(.*)/);` – Shomz Dec 23 '14 at 18:13