简体   繁体   中英

How do I split a value using the split function from javascript to split checking only the first and last occurence

So I need to split an regex that's coming from my database. The value is like the following

regexValue = '/^([0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}|[0-9]{2}\.?[0-9]{3}\.?[0-9]{3}\/?[0-9]{4}\-?[0-9]{2})$/ig'

if you analyze throughly this regex you can see that it have an forward slash '/' between the regex. So if I wanted to split it, using

values.split('/'); 

It would generate more strings than I would like to. For example a simple regex

//would generate three values("", \w+ , ig)    
regexValue = '/\w+/ig'
regexValue.split('/');

Is there a way so I could only split getting the first and last values?

If you want to split that string into the regular expression bodyand its flags, you can do that easily with...a regular expression. 😃

const parts = /^\s*\/(.*)\/(?:([a-z]*))\s*$/.exec(regexString);
//           A ^
//           B  ^^^
//           C     ^^
//           D       ^^^^
//           E           ^^
//           F             ^^^^^^^^^^^^
//           G                         ^^^
//           H                            ^
  • A: Start of input
  • B: Optional whitespace
  • C: Leading slash of regex "literal"
  • D: Body of the expression
  • E: Ending slash of regex "literal"
  • F: Optional flags
  • G: Optional whitespace
  • H: End of input

Live Example:

 const regexString = '/^([0-9]{3}\\\\.?[0-9]{3}\\\\.?[0-9]{3}\\\\-?[0-9]{2}|[0-9]{2}\\\\.?[0-9]{3}\\\\.?[0-9]{3}\\\\/?[0-9]{4}\\\\-?[0-9]{2})$/ig'; const parts = /^\\s*\\/(.*)\\/(?:([az]*))\\s*$/.exec(regexString); if (!parts) { console.log("No match"); } else { const [, body, flags] = parts; console.log(`body: ${body}`); console.log(`flags: ${flags}`); }


Note that I escaped the backslashes in the string literal, since you said you're reading this from your database, you don't have it in a string literal in your code. It's just that inside a string literal, a backslash is an escape character, so \\. and . mean exactly the same thing. To write a string literal defining a string with backslashes in it, you have to escape them as I've done in the snippet above. Again, you've said it comes from your database, so you're fine, but I figured I should escape them in the example to avoid being misleading.

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