Correct way to do a string replace with regex in javascript?

I am a newbie to regex and my expression appears to be backwards or opposite of what I am trying to do. I have a string, in this case a url, and I basically want to replace everything up to and including the last forward slash with an empty string. Currently I have

"".replace(/[^/]+$/, "")

which basically does the opposite of what I want. What is the proper expression to get the results I'm seeking? Which in this case would be to end up with a string "other"? Thanks for any help

RegExr example


You want a regex that matches the beginning of the string, followed by as many characters as possible, followed by a slash:


You don't even need RegExp for this. You just need the position of the last / and cut the string starting just after it.

var str = "";

var other = str.substr(str.lastIndexOf('/')+1);

You could also do splitting by / and get the last entry in the resulting array, but string manipulation is way faster most of the time.


Going with your original logic of using a replacement

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

<!DOCTYPE html>

<p id="demo"></p>

<button onclick="myFunction()">Try it</button>

function myFunction()
var re=/^.*[\/]/
var str=document.getElementById("demo").innerHTML; 
var n=str.replace(re, '');




and pulling the value from the first group match

Here are 2 other solutions (same as /^.*\//), if you like to avoid errors in jslint

console.log("".replace(/^[\S\s]*\//, ""));
console.log("".replace(new RegExp("\.*\\/"), ""));

On jsfiddle

And just to offer another method that does not require regex


on jsfiddle

Need Your Help

Custom upload field in wordpress user profile

php wordpress file-upload

I'm trying to allow users to upload a profile image on their user profile editing page, here's the code for the upload form:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.