n00*_*101 260 javascript string match
可能重复:
Javascript StartsWith
我知道我可以这样做^ =看看id是否以某个东西开头,我尝试使用它,但它没有用......基本上,我正在检索网址,我想要设置一个类对于以某种方式开始的路径名元素...
所以,
var pathname = window.location.pathname; //gives me /sub/1/train/yonks/459087
Run Code Online (Sandbox Code Playgroud)
我想确保对于以/ sub/1开头的每个路径,我可以为元素设置一个类......
if(pathname ^= '/sub/1') { //this didn't work...
...
Run Code Online (Sandbox Code Playgroud)
Phi*_*lds 368
if (pathname.substring(0, 6) == "/sub/1") {
// ...
}
Run Code Online (Sandbox Code Playgroud)
Ric*_*res 182
String.prototype.startsWith = function(needle)
{
return this.indexOf(needle) === 0;
};
Run Code Online (Sandbox Code Playgroud)
Cro*_*ros 83
您也可以使用string.match()和正则表达式:
if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes
Run Code Online (Sandbox Code Playgroud)
string.match()如果找到则返回匹配子串的数组,否则返回null.
Rob*_*ohr 38
一个更可重用的功能:
beginsWith = function(needle, haystack){
return (haystack.substr(0, needle.length) == needle);
}
Run Code Online (Sandbox Code Playgroud)
小智 23
首先,让我们扩展字符串对象.感谢里卡多佩雷斯的原型,我认为使用变量'string'在使其更具可读性的情况下比'needle'效果更好.
String.prototype.beginsWith = function (string) {
return(this.indexOf(string) === 0);
};
Run Code Online (Sandbox Code Playgroud)
然后就像这样使用它.警告!使代码极具可读性.
var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
// Do stuff here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
344841 次 |
| 最近记录: |