【问题标题】:Dynamically find pieces of phrase in string using regex and .replace()使用正则表达式和 .replace() 在字符串中动态查找短语
【发布时间】:2018-12-07 08:18:22
【问题描述】:

我有一个大字符串,我需要删除短语“Pages 1 of 3 Printed on:”,我正在尝试使用正则表达式使 X 的 1 变为动态。我也尝试过使用通配符和字符串模板,但我没有运气。

我目前正在对其进行硬编码。例如,如果我硬编码 3,它会找到整个短语,将其替换为空,并找到任何其他实例。任何帮助表示赞赏!

let text = 'Pages 1 of 3 Printed on: FIRST NAME Pages 2 of 3 Printed on: TITLE SIGNATURE Pages 3 of 3 Printed on: STAN SMITH'


// Remove Pages
if (text('Pages 1 of ' + /[0-9]/ + 'Printed on: ')) {
    // Removing Begins
    console.log('Removing: Pages 1 of ' + /[0-9]/ + 'Printed on: ');

    // Remove Text
    text = text('Pages 1 of ' + /[0-9]/ + 'Printed on: ', '');

    // Find Any Other Instances Of Text
    while (text.includes('Pages 1 of /[1-9]/gPrinted on: ', '')) {
        text = text('Pages 1 of ' + /[0-9]/ + 'Printed on: ', '', '');
    }

    // Removing Ends
    console.log('Removed: Pages 1 of ' + /[0-9]/ + 'Printed on: ');
}

【问题讨论】:

    标签: javascript regex string


    【解决方案1】:

    您可以使用(全局)正则表达式:

    /Pages \d+ of \d+ Printed on: /g
    

    let text = 'Pages 1 of 3 Printed on: FIRST NAME Pages 2 of 3 Printed on: TITLE SIGNATURE Pages 3 of 3 Printed on: STAN SMITH';
    const output = text.replace(/Pages \d+ of \d+ Printed on: /g, '');
    console.log(output);

    【讨论】:

    • “正则表达式”概念对我来说是一个新概念,所以谢谢!
    • 当某个答案解决了您遇到的问题时,请考虑将其标记为已接受以表明问题已解决:)
    【解决方案2】:

    我并不完全是其余代码的样子,但如果你想打印 X 的 1 并增加 X 的值,你可以这样做:

    for (let i in pages) console.log(`Printing page ${i+1} of ${pages}`);

    这是如果pages 是一个整数。

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 2022-06-15
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多