i need to get a specific string using javascript or jquery

89 Views Asked by At

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();

2

There are 2 best solutions below

0
Mainul Islam Faruqi On BEST ANSWER

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
1
Selaka Nanayakkara On

In vanila javascript you can use a regex like below :

function extractBasePath(url) {
    const match = url.match(/^(\/[^/]+\/[^/]+\/[^/]+)(\/|$)/);
    return match ? match[1] : null;
}

const url = "/projectx/index.php/Home/index";
const basePath = extractBasePath(url);
console.log(basePath)

In PHP you can come up with something like :

function extractBasePath($url) {
    $parsedUrl = parse_url($url);
    $path = $parsedUrl['path'];
    $basePath = dirname($path);
    $basePath = '/' . trim($basePath, '/');
    return $basePath;
}

$url = "/projectx/index.php/Home/index";
$basePath = extractBasePath($url);

echo $basePath; // Output: "/projectx/index.php/Home"