简体   繁体   中英

Regular Expressions javascript how to check aa_bb

I'm trying to look for 2 digit string in URL. For example:

www.abc.com/ff_gg/abc

I can check it with:

if (window.location.href.indexOf("ff_gg") > -1) {
    // 
} else ...

but ff _ gg can be a random string. How to use regex to save ff and gg from a url as a variable ? ff and gg will be separated by _ .

You can use String#search with a regex, instead of String#indexOf . Or RegExp#test

Also see RegExp to understand the expression.

 const text = 'www.abc.com/ff_gg/abc'; const rx = /\\/[az]{2}_[az]{2}\\//i; if (text.search(rx) > -1) { console.log('found'); } else { console.log('not found'); } if (rx.test(text)) { console.log('found'); } else { console.log('not found'); } 

You could use a similar regex to String#match and capture, or RegExp#exec .

Alternatively use string manipulation with String#split or String#slice .

As you see, there are several options (and even more that I've not mentioned) but I don't have time just now to create an example for each.

 const text = 'www.abc.com/ff_gg/abc'; const match = text.match(/\\/([az]{2})_([az]{2})\\//i); if (match) { console.log(match); } 

 const text = 'www.abc.com/ff_gg/abc'; const rx = /\\/[az]{2}_[az]{2}\\//i; const index = text.search(rx); if (index > -1) { console.log(text.slice(index + 1, index + 1 + 5).split('_')); } 

([a-zA-Z]{2})_([a-zA-Z]{2})

2 capturing groups separated by _ can do the trick for the regex.

Then use match() who will return the matched groups

demo

In javascript you can make a RegExp object. For more information about the RegExp object see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

The following example should work:

 var url = "www.abc.com/ff_gg/abc"; var reg = new RegExp("([a-zA-Z]{2})_([a-zA-Z]{2})"); if (reg.test(url)) { var matches = url.match(reg); var ff = matches[1]; var gg = matches[2]; console.log("group1: " + ff); console.log("group2: " + gg); console.log("do something"); } 

Here is also a example of the regex: http://regexr.com/3e8a7

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