JS正则表达式基于组查找和替换



我正在尝试搜索两个字符:1.', '和2.'('。 因此,如果找到逗号和空格,则仅替换为逗号,如果找到(,请替换为空白。

以下是我所拥有的,我知道我可以做两个替换,但正在寻找使用可能的组组合成一个......喜欢$1 ='' $2 = ','

str.replace(/(()|(,s)/g, '');

replace函数接受函数作为第二个参数。您可以使用它来替换您想要的任何匹配项。函数的第一个参数是匹配的字符串。

在此处查看更多详细信息。

您可以使用捕获的组和反向引用:

str = str.replace(/(,) |(/g, '$1');

代码示例:

var str = 'abc, 123( something.'
console.log(str.replace(/(,) |(/g, '$1'))
//=> "abc,123 something."

正则表达式演示

两个步骤:

将"、"改为","

const regex = /(,s)/gm;
const str = `abc, 123( something.`;
const subst = `,`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

将")"改为"

const regex = /(()/gm;
const str = `abc, 123( something.`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

混合溶液:

    regex = /(,s)/gm;
    str = `abc, 123( something.`;
    subst = `,`;
    
    // The substituted value will be contained in the result variable
    result = str.replace(regex, subst);
    
    regex = /(()/gm;
    str = result;
    subst = ``;
    
    // The substituted value will be contained in the result variable
    result = str.replace(regex, subst);
    //
    console.log(result);

如果我帮助你,记得把我标记为问题的答案

String.prototype.replace的第二个参数可以是字符串或函数。源

更换功能

如果它是一个函数,则将为每个匹配项调用它,并且其返回值将用作替换文本。

function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
  return replacement;
}

更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement

替换字符串

console.log(
  "Your age: 50".replace(/.+?(?<age>d+)/, "age named capure group: $<age>")
);

有关可在替换字符串中使用的内容的详细信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement

最新更新