简体   繁体   English

如果字符串包含空格 javascript,则不匹配

[英]don't match if string contains a whitespace javascript

I am trying to figure out the regex pattern for not matching strings if the string contains whitespace.如果字符串包含空格,我试图找出不匹配字符串的正则表达式模式。 For example例如

"The " should not match "The" “The”不应与“The”匹配

"House " should not match "House" “房子”不应该匹配“房子”

You can check whether the search string is inside any of the books in your list.您可以检查搜索字符串是否在列表中的任何书籍内。

var matches = function(search, books) {
  return books.filter(function(book) {
    return book.indexOf(search) !== -1
  })
}

I do not think you need regex in this case.我认为在这种情况下您不需要正则表达式。

See that 'house ' is not inside 'house' but is inside 'house of'看到“房子”不在“房子”里面,而是在“房子的”里面

You can use startsWith() that fits well to your requirement, use the polyfill for older/unsupported browsers.您可以使用适合您的要求的startsWith() ,将 polyfill 用于较旧的/不受支持的浏览器。

 var strings = ["HouseArrest", "House arrest", "HouseOfCards", "House of cards"]; function search(val){ var res = strings.filter(i=>i.startsWith(val)); console.clear(); console.log(JSON.stringify(res)); }
 <input onkeyup="search(this.value)" type="text"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM