简体   繁体   中英

Unable to construct regular expression in JavaScript

My requirement is something like this :

var actualstring = 'sales/salesorder/newOrder';

I'm writing a function which returns true if after sales/ , there is a string and a forward slash (/). It has to return false if after sales/ , there is just a string.

For example:

var actualstring = 'sales/salesorder/newOrder'; // should return true.  
var actualstring = 'sales/salesorder'; // should return false.  
var actualstring = 'sales/Invoice/InvoiceDetails'; // should return true.    
var actualstring = 'sales/Invoice/InvoiceDetails/View'; // should return true.   
var actualstring = 'sales/Invoice'; // should return false  

So for this I have some regular expression like this :

var term = 'sales/Invoice/InvoiceDetails/View';
var re = new RegExp("^(/sales/[a-z0-9]{5,}/[a-z0-9]{5,}{/})$");
if (re.test(term)) {
    console.log("Valid");
} else {
    console.log("Invalid");
}

This clearly seems to be not working and completely lost in all the symbols.

Sounds like you want to use

/^sales\/[a-zA-Z0-9]+\//

where ^ = start of string, followed by sales/ , followed by at least one alphanumeric character, up to any number of them, followed by a /

 var strings = ['sales/salesorder/newOrder', // should return true. 'sales/salesorder', // should return false. 'sales/Invoice/InvoiceDetails', // should return true. 'sales/Invoice/InvoiceDetails/View', // should return true. 'sales/Invoice']; // should return false console.log(strings.map(el => !!el.match(/^sales\\/[a-zA-Z0-9]+\\//)))

This should work for what you have described:

var term = 'sales/Invoice/InvoiceDetails/View';
var re = new RegExp("^(sales\/[a-zA-Z0-9]{5,}\/.*)$");
if (re.test(term)) {
  console.log("Valid");
} else {
  console.log("Invalid");
}
  • Forward slack / needs to be escaped with a backslash. Like \\/
  • Your test string also contains capital letters, so AZ needs to be checked too.
  • There is a leading / in your your regEx but not in test string.

You can divide your regex into four groups

  1. String should start with sales - (^sales)
  2. Then there should be a forward slash - (\\/)
  3. Then there should be a word - ([a-zA-Z0-9]+)
  4. Then there should be a forward slash - (\\/)

So your complete regex will be

(^sales)(\\/)([a-zA-Z0-9]+)(\\/)

Here is sample code

 let samples = ['sales/salesorder/newOrder', 'sales/salesorder', 'sales/Invoice/InvoiceDetails', 'sales/Invoice/InvoiceDetails/View', 'sales/Invoice'] let regex = /(^sales)(\\/)([a-zA-Z0-9]+)(\\/)/ for(let sample of samples){ console.log(regex.test(sample)) }

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