javascript - 如何在忽略空格的情况下匹配另一个字符串中的字符串

标签 javascript string match

我有一个要搜索的字符串,我需要匹配并返回搜索字符串开头的另一个字符串。正在搜索的字符串中可能有空格,为了搜索的目的需要忽略它,但仍然准确返回。要匹配的字符串中永远不会有空格。

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/

相关文章:

javascript - 将一个元素固定在右边并减少它在左 ->右方向的宽度

javascript - 无法使用 Masonry 布局达到预期效果

c++ - 公共(public)图书馆的 char 或 std::string 数组?

r - 选择一个数据框中与另一数据框中的行部分匹配的行

vba - 搜索字符串并查找相邻列的内容

javascript - 删除 svg 矩形绘制行中的魔数(Magic Number)

java - 如果你不引用它,Java 中的对象会发生什么,就像这里的 : myString. concat ("that")

javascript - 如何将一个复杂的字符串分成 3 个独立的数组?

arrays - 如何匹配 token 前的非字母?

javascript - 如何在 TypeScript 中为 Node 使用无类型的 JS NPM 模块?