Here my var =

var path = '';

how to remvoe the last forward slash or test/

Thanks in advance

Dani AI

Generated

As 's answer is a practical fix, here are a few alternative approaches and gotchas so the change is reliable in different situations (raw URL string vs. HTML anchor vs. URLs with query/hash).

For removing a single trailing slash from a plain string, use a replace that only matches a slash at the very end:

url = url.replace(/\/$/, '');

See String.prototype.replace for details. This will not touch protocol markers (like the // in http://) because it only matches the final character.

To remove the entire last path segment (the last folder or filename) from a URL-like string, use a pattern that strips everything after the final slash:

url = url.replace(/\/[^\/]*$/, '');

If the value can include query strings or fragments, operate on the pathname with the URL API instead of raw regex so you do not accidentally remove query/hash content:

var u = new URL(urlString, window.location.origin); // base needed for relative URLs
if (u.pathname !== '/') {
  u.pathname = u.pathname.replace(/\/$/, '');
}
urlString = u.toString();

See URL for behavior and browser support notes.

If the variable contains an HTML anchor (as in 's post), parse and update both the href attribute and the visible text. Use getAttribute/setAttribute to avoid the browser auto-resolving the href:

var doc = new DOMParser().parseFromString(htmlString, 'text/html');
var a = doc.querySelector('a');
if (a) {
  a.setAttribute('href', a.getAttribute('href').replace(/\/$/, ''));
  a.textContent = a.textContent.replace(/\/$/, '');
}
htmlString = a ? a.outerHTML : htmlString;

See DOMParser. Choose the method that matches whether the input is plain URL text, a full URL with query/hash, or an HTML fragment.

Recommended Answers

All 2 Replies

Member Avatar for Member #905211

Try this:

var path = '';

var lastIndex = path.lastIndexOf('/');
path = path.substring(0, lastIndex);
//becomes 

just remember that if you have as your path it will become

Thanks stbuchok, Its done

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.