2

How can i remove sub string (after last slash) from string in javascript like

c:/Program File/Internet Explorer

to

c:/Program File/

6 Answers6

6

Try lastIndexOf()

var str = "c:/Program File/Internet Explorer";
var newStr = str.substr(0,str.lastIndexOf("/")+1);

document.getElementById("res").innerHTML = newStr;
<div id="res"/>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
5

You may try the below negated char class based regex.

string.replace(/[^\/]*$/, "")

DEMO

  • [^\/]* matches any char but not forward slash zero or more times.

  • $ asserts that we are at the end of a line.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

Check out http://www.regexr.com if you want to test regular expressions. Something like .*/ would match everything up to the slash character.

Luke
  • 1,724
  • 1
  • 12
  • 17
0
var str = "c:/Program File/Internet Explorer";
var output = str.slice(0, str.lastIndexOf("/")+1);
A Web-Developer
  • 868
  • 8
  • 29
0

You need lastIndexOf and substr

var t = "c:/Program File/Internet Explorer";
t = t.substr(0, t.lastIndexOf("/"));
alert(t);

or you can use the following.

    var removeLastPart = function(url) 
{
        var lastSlashIndex = url.lastIndexOf("/");
        if (lastSlashIndex > url.indexOf("/") + 1)
{
            return url.substr(0, lastSlashIndex);
        } 
else 
{
            return url;
        }
    }
itzmebibin
  • 9,199
  • 8
  • 48
  • 62
0
var filePath = "c:/Program File/Internet Explorer";
var displayUptoSpecifiedChar = filePath.lastIndexOf('/') + 1;
console.log(filePath.slice(0, displayUptoSpecifiedChar));
Parthipan S
  • 180
  • 9