简体   繁体   中英

Using a regular expression in JavaScript

I'm trying to develop an application that selects words in the following pattern: ([az] * \\. [az] *) , made the following JavaScript function and executed it in XUL Explorer.

<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="yourwindow"
        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
        xmlns:html="http://www.w3.org/1999/xhtml"
        xmlns:h="http://www.w3.org/1999/xhtml">
  <button label="click" oncommand="fpatt()" />

  <script type="text/javascript"> <![CDATA[ // put some js code here
    function fpatt(){
      var text = "supermercardo, tooc hip.ermercadotoooooc, mercado"; 
      var patt = "([a-z]*\.[a-z]*)"; 
      alert( text.match( patt ) );
    }
  ]]> </script>
</window>

The result is in the alert: supermercardo,, supermercardo, ; when I run the same script on the site selected is the result regexpal.com: ip.mercadotoooooc .

"([az]*\\.[az]*)" is not a regular expression - it is a string. And in a string \\. is exactly the same as . . To have your regular expression interpreted as a regular expression you should specify it as a regular expression literal:

var patt = /([a-z]*\.[a-z]*)/;

See http://jsfiddle.net/N6qj7/ for your code with this change (and - no, this has absolutely nothing to do with XUL, just old plain JavaScript).

Documentation

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