首页 > 解决方案 > 使用正则表达式和 .replace() 在字符串中动态查找短语

问题描述

我有一个大字符串,我需要删除短语“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: ');
}

标签: javascriptregexstring

解决方案


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

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

这是如果pages是一个整数。


推荐阅读