简体   繁体   中英

Regex to match all characters in javascript

I have a text input field in which a user can enter some text. Starting with 1 character, I want to match all elements containing that character.

Elements: (array: messages)

  • Hi
  • Hello
  • Good
  • Dog

When I enter 'H', the first 2 elements should match.

When I enter 'E', the second element should match.

When I enter 'HI', the first element should match.

And so on...

Anyway, I want to match ALL characters. When I enter a letter or a number it works, but when I enter a parenthesis, I get the following error: Invalid regular expression: unmatched parentheses

My regex:

messages.filter(e => e.match(new RegExp(filterQuery, 'i')))
var txt ="h";
var reg = new RegExp(txt,'i');
var filterarr= arr.filter(e => reg.exec(e));

 <html> <head> <title>Regex to match all characters in javascript</title> </head> <body> Array: <div id="div"></div> <br /> Filter Array: <div id="divfilter"></div> <script> var arr = ["Hi","Hello","Good","Dog"]; document.getElementById("div").innerHTML = getString(arr); var txt ="h"; var reg = new RegExp(txt,'i'); var filterarr= arr.filter(e => reg.exec(e)); document.getElementById("divfilter").innerHTML = getString(filterarr); function getString(arr){ var str=""; for(let i =0;i<arr.length;i++){ if(i,=0) str+="; "; str += arr[i]; } return str; } </script> </body> </html>

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