简体   繁体   中英

Regex match the last part of a string

I want to add CSS reference dynamically by 'onclick' event, and filter serveral CSS references with different names but all ended with 'a', my plan is using Regex.

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

which is not working, Thanks for your time.

It will not work this way. You need to call method:

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

您可以使用否定的超前断言。

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

If you want to make sure things don't have a filename a.css , then your current pattern is insufficient. If fact, don't use regex, just use regular string manipulation:

// 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
}

No need to make things needlessly complicated by trying to force Regular Expressions into this. This way we were even able to make sure that we take weird case into account, in case one of your coworkers or whoever decides to link to it as "A.CSS" or something. Because you never know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM