简体   繁体   中英

Javascript RegExp Curly Brace and test Issue

I want regExp to test for two 'Hello'-s and return true but it only returns false even though I cannot find anything wrong with my code. How do I fix this? Please also suggest what is wrong with the code.

<html>
<body>

<script type="text/javascript">

var str ="Hello Hello";
var patt = /(hello){2}/gi;
var result =patt.test(str);
document.write("Returned value: " + result); 
</script>
</body>
</html>

You can use the match() method which searches for a match between a regular expression and a string, and returns the matches.

   var result = "Hello hello".match(/Hello/gi); // Array { 0="Hello", 1="hello"}

   result.length // 2

If you want to use search instead of match:

   "hello hello ".search(/(hello ?){2}/gi); // it returns 0 when it find two occurrences of hello
                                            // if not it returns -1

You forgot the space:

var patt = /(hello ?){2}/gi;

Your original RE matches "HelloHello", but not two occurences of "Hello".

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