Search code examples
javascriptphpjquerystringtrim

i need to get a specific string using javascript or jquery


i have a string like this

var x = "/projectx/index.php/Home/index"

i need a function to affect this sring to get an output value:

y = "/projectx/index.php/Home"

means to right trim and remove last word with separator "/" also means the same function used in PHP

$y = rtrim($x, "/");

javascript doesn't have rtrim();


Solution

  • Using JavaScript

    function removeLastSegment(url) {
        return url.slice(0, url.lastIndexOf("/"));
    }
       
    var x = "/projectx/index.php/Home/index";
    var y = removeLastSegment(x);
    
    console.log(y);
    // Output: /projectx/index.php/Home