15

If I have a string loaded into a variable, what's the appropriate method to use to determine if the string ends in "/" forward slash?

var myString = jQuery("#myAnchorElement").attr("href");
2

6 Answers 6

22

A regex works, but if you want to avoid that whole cryptic syntax, here's something that should work: javascript/jquery add trailing slash to url (if not present)

var lastChar = url.substr(-1); // Selects the last character
if (lastChar !== '/') {         // If the last character is not a slash
   ...
}
Sign up to request clarification or add additional context in comments.

Comments

3

Use regex and do:

myString.match(/\/$/)

Comments

2

A simple solution would be to just check the last character via:

var endsInForwardSlash = myString[myString.length - 1] === "/";

EDIT: Keep in mind, you would need to check that the string is not null first to keep from throwing an exception.

Comments

2

You can use substring and lastIndexOf:

var value = url.substring(url.lastIndexOf('/') + 1);

Comments

1

You don't need JQuery for that.

function endsWith(s,c){
    if(typeof s === "undefined") return false;
    if(typeof c === "undefined") return false;

    if(c.length === 0) return true;
    if(s.length === 0) return false;
    return (s.slice(-1) === c);
}

endsWith('test','/'); //false
endsWith('test',''); // true
endsWith('test/','/'); //true

You can also write a prototype

String.prototype.endsWith = function(pattern) {
    if(typeof pattern === "undefined") return false;
    if(pattern.length === 0) return true;
    if(this.length === 0) return false;
    return (this.slice(-1) === pattern);
};

"test/".endsWith('/'); //true

Comments

0

Now you can do that already natively with modern javascript:

mystring.endswith('/')

This feature has been introduced since ES2015 and works well in all browsers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.