简体   繁体   中英

JS Removing non-alphabetic characters with “new RegExp()” from string

I have a search input that allows me to filter the results of a list based on what the user inputs. Although I want to remove all non-alphabetic characters both from the search input and from the list as well I guess, so they can find the match.

This is what I currently have:

let searchInput = '' // whatever the user types

let result = list.filter(element => element.name.match(new RegExp(searchInput, 'i')))
    .sort((a, b) => true * a.name.localeCompare(b.name))

You can replace non word characters with the regex /[\\W_]+/ .

It's not clear whether you trying to replace the existing data or make a new filtered list. I'll assume the later.

First use map() to make a list with the non-words characters removed, then remove the non-word characters from the search input. Then just filter. You can chain them up if you like:

 let searchInput = 'he*(llo' // whatever the user types let list = [ {name: '#hello'}, {name: 'he$llo'}, {name: 'someevalue'}, {name: 'what'}, {name: 'hello%'} ] let re = new RegExp(/[\\W_]+/i) let cleaned_list = list.map(i => (i.name = i.name.replace(re, ''), i)) let cleaned_input = searchInput.replace(re, '') let result = cleaned_list.filter(element => element.name.match(new RegExp(cleaned_input))) console.log(result) 

If you only want to match based on the strings without non-character words, but want the original terms in your final result, don't clean the list first, just clean each element as you filter:

 let searchInput = 'he*(llo' // whatever the user types let list = [ {name: '#hello'}, {name: 'he$llo'}, {name: 'someevalue'}, {name: 'what'}, {name: 'hello%'} ] let re = new RegExp(/[\\W_]+/i) let cleaned_input = searchInput.replace(re, '') let result = list.filter(element => element.name.replace(re, '').match(new RegExp(cleaned_input))) console.log(result) 

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