简体   繁体   中英

Dynamically find pieces of phrase in string using regex and .replace()

I have a large string I need to removed the phrase "Pages 1 of 3 Printed on:" and I'm trying to use regex to make the 1 of X to be dynamic. I've also tried using the wildcard and string template, but I'm having no luck.

I currently have it working hard coded. For example, if I hard code 3, it will find the entire phrase, replace it with nothing, and find any other instances. Any help is appreciated!

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: ');
}

You can use the (global) regular expression:

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

I'm not completely what the rest of the code looks like, but if you want to print 1 of X with incrementing value of X, you could do:

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

This is if pages is an int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM