[英]Check if String Contains a Substring With “Catch All” Items
I'm looking to make a javascript function that can identify when a string contains a substring with a "catch all" item.我正在寻找一个 javascript function 可以识别字符串何时包含 substring 与“全部”项目。
Example:例子:
const contains = (string, substring) => ...
let string1 = "The blue dog eats."
let string2 = "The red dog eats."
let string3 = "The purple dog sleeps."
let substring = "The * dog eats"
// * is a catch all for any string
contains(string1, substring) // true
contains(string2, substring) // true
contains(string3, substring) // false
How would I go about making a function like this?我将如何 go 像这样制作 function ? Would I use regex for this?
我会为此使用正则表达式吗?
Here is how to write the regular expression for your question:以下是如何为您的问题编写正则表达式:
var txt = ...;
if (/^The .* dog eats$/.test(txt)) {
...
}
This matches your requirements这符合您的要求
function contains(testString, subString){
var subStringParts = subString.split("*");
var testRegex = new RegExp(subStringParts.join(".*"));
return testRegex.test(testString);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.