正则表达式匹配字符串的最后一部分

时间:2015-08-01 03:12:05

标签: javascript regex

我想通过'onclick'事件动态添加CSS引用,并使用不同的名称过滤几个CSS引用,但都以'a'结尾,我的计划是使用正则表达式。

if (cssRef != /.*a.css$/){
  then add the css reference
}

这是行不通的,谢谢你的时间。

3 个答案:

答案 0 :(得分:2)

它不会以这种方式工作。你需要调用方法:

if (!(/.*a\.css$/).test(cssRef)) { ... }

答案 1 :(得分:1)

您可以使用否定先行断言。

if (/^(?!.*a\.css$)/.test(cssRef)) { ... }

答案 2 :(得分:1)

如果您想确保某些内容不具有文件名// split the HREF on slashes. If there are no slashes, this will // be an array with just the filename in position [0]. var terms = cssRef.split('/'); // get the last element in that array, which will be the filename: var last = terms.slice(-1)[0]; // is that filename not "a.css"? Excellent, do stuff here. if (last.toLowerCase() !== "a.css") { // we know this isn't a file called a.css } ,那么您当前的模式就不够了。事实上,不要使用正则表达式,只需使用常规的字符串操作:

@Table

不要试图强制使用正则表达式来使事情变得不必要。通过这种方式,我们甚至可以确保我们将奇怪的情况考虑在内,以防你的一个同事或任何决定链接到它的人#34; A.CSS"或者其他的东西。因为你永远不知道。