用于查找字符串是否以正斜杠结尾的Javascript

Javascript to find if string terminates in a forward slash

本文关键字:结尾 Javascript 查找 字符串 是否 用于      更新时间:2023-09-26

如果将字符串加载到变量中,那么确定字符串是否以"/"正斜杠结尾的合适方法是什么?

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

正则表达式是有效的,但如果你想避免整个神秘的语法,这里有一些应该有效的东西:javascript/jquery将尾部斜杠添加到url(如果不存在)

var lastChar = url.substr(-1); // Selects the last character
if (lastChar !== '/') {         // If the last character is not a slash
   ...
}

使用regex并执行:

myString.match(/'/$/)

一个简单的解决方案是通过检查最后一个字符

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

EDIT:请记住,您需要首先检查字符串是否为null,以防止引发异常。

您可以使用子字符串和lastIndexOf:

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

您不需要JQuery。

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

你也可以写一个原型

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

现在,您可以使用现代javascript:在本机上实现这一点

mystring.endswith('/')

此功能自ES2015开始引入,在所有浏览器中都能很好地工作。