Search code examples
javascriptregexregexp-replace

combining multiple regex into single


I have long string and I want to replace some chars with empty. I have following regex

  1. 1st I want to remove all url from string, for which I have regex /(?:https?|ftp):\/\/[\n\S]+/i

  2. Next I want to remove all word which starts with Car followed by nine digits. Car word should case insensitive, regex for that /car\s*\d{9}/i

  3. And Last I want to remove all special chars from string, regex for that /[^\w\s]/gi

So my input string like below

Input Hell Test https://regex101.com with special Car123456789dgd cha cAr12345678racters @##!$#!@Hekki

OutputHell Test with special dgd cha cAr12345678racters Hekki

currently I have to do 3 separate operation to do this, Is there any way I can combine these regex into one?

I try to join using | but didn't work. (/(?:https?|ftp):\/\/[\n\S]+/i)|(/car\s*\d{9}/i)|(/[^\w\s]/gi)


Solution

  • Use | to combine:

    const str = 'Hell Test https://regex101.com with special Car123456789dgd cha cAr12345678racters @##!$#!@Hekki';
    console.log(str.replace(/(?:https?|ftp):\/\/[\n\S]+|car\s*\d{9}|[^\w\s]/gi, ''));