使用正则表达式和.replace()

时间:2018-12-07 08:18:23

标签: javascript regex string

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

2 个答案:

答案 0 :(得分:0)

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

/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);

答案 1 :(得分:0)

我并不完全明白其余代码的样子,但是如果您要打印X的1且X的值递增,则可以执行以下操作:

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

这是pages是一个整数。