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

"http://www.sweet.com/member/other".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

Answers


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 = "http://www.sweet.com/member/other";

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.


This

Going with your original logic of using a replacement

"http://www.sweet.com/member/other".replace(/^.*[\/]/, "")

<!DOCTYPE html>
<html>
<body>


<p id="demo">http://www.sweet.com/member/other</p>

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

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

</body>
</html>

OR

^(?:.*/)(.*?)$

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("http://www.sweet.com/member/other".replace(/^[\S\s]*\//, ""));
console.log("http://www.sweet.com/member/other".replace(new RegExp("\.*\\/"), ""));

On jsfiddle

And just to offer another method that does not require regex

console.log("http://www.sweet.com/member/other".split("/").slice(-1)[0]);

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.