检查字符串是否以某些内容开头?
我知道我可以像 ^=
那样查看 id 是否以某些内容开头,并且我尝试使用它来实现此目的,但它不起作用。基本上,我正在检索一个 URL,并且想为以某种方式开头的路径名的元素设置一个类。
示例:
var pathname = window.location.pathname; //gives me /sub/1/train/yonks/459087
我想确保对于以 /sub/1
开头的每个路径,我可以为元素设置一个类:
if (pathname ^= '/sub/1') { //this didn't work...
...
I know that I can do like ^=
to see if an id starts with something, and I tried using that for this, but it didn't work. Basically, I'm retrieving a URL and I want to set a class for an element for path names that start in a certain way.
Example:
var pathname = window.location.pathname; //gives me /sub/1/train/yonks/459087
I want to make sure that for every path that starts with /sub/1
, I can set a class for an element:
if (pathname ^= '/sub/1') { //this didn't work...
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 stringObject.substring
Use stringObject.substring
您可以使用 string.match() 和正则表达式对于这一点,
string.match()
将返回一个匹配子字符串的数组(如果找到),否则null。You can use string.match() and a regular expression for this too:
string.match()
will return an array of matching substrings if found, otherwise null.更可重用的功能:
A little more reusable function:
首先,让我们扩展字符串对象。感谢 Ricardo Peres 的原型,我认为使用变量“字符串”比“针”效果更好,使其更具可读性。
然后你就这样使用它。警告!使代码极具可读性。
First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.
Then you use it like this. Caution! Makes the code extremely readable.
查看 JavaScript
substring()
方法。Have a look at JavaScript
substring()
method.