我有一个要搜索的字符串,我需要匹配并返回搜索字符串开头的另一个字符串。正在搜索的字符串中可能有空格,为了搜索的目的需要忽略它,但仍然准确返回。要匹配的字符串中永远不会有空格。
stringA = "ThisIsAString";
与 stringB 相比应给出以下结果:
stringB = "This Is A String"; //"This Is A String"
stringB = "ThisIsAlsoAString"; //undefined
stringB = "ThisIs A String With Extra Words At The End"; //"ThisIs A String"
stringB = "Hey, ThisIsAString"; //undefined
什么是有效的方法来做到这一点?
最佳答案
您可以使用 \s*
来匹配零个或多个空格。通过下面的代码,我们在每个字符之间放置一个匹配器。
const stringA = "ThisIsAString";
const tests = [
"This Is A String",
"ThisIsAlsoAString",
"ThisIs A String With Extra Words At The End",
"Hey, ThisIsAString",
];
const optionalSpaces = '\\s*';
const results = tests.map(test =>
test.match(
new RegExp(stringA.split('').join(optionalSpaces))
)
);
console.log(results);
关于javascript - 如何在忽略空格的情况下匹配另一个字符串中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44758190/