Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to find if string terminates in a forward slash

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");
like image 377
RegEdit Avatar asked Feb 08 '13 16:02

RegEdit


People also ask

How do you check if a string ends with a substring in JavaScript?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.

How do you get the string after the last slash?

First, find the last index of ('/') using . lastIndexOf(str) method. Use the . substring() method to get the access the string after last slash.

How do you escape a forward slash in JavaScript?

We should double for a backslash escape a forward slash / in a regular expression. A backslash \ is used to denote character classes, e.g. \d . So it's a special character in regular expression (just like in regular strings).

What indicates end of the string in JavaScript?

The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate. This method is case-sensitive.


2 Answers

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
   ...
}
like image 197
isherwood Avatar answered Oct 13 '22 13:10

isherwood


Use regex and do:

myString.match(/\/$/)
like image 29
Darren Avatar answered Oct 13 '22 11:10

Darren