javascriptregexstringspecial-characters

how to match '\u' codes for all the emojis with regexp?


I want to find match all the strings which will have emojis in the form of \u codes. I'm trying with below regexp but is not working.

/([\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2694-\u2697]|\uD83E[\uDD10-\uDD5D])/g

But, it is not detecting. I want to match and get

\ud83d\ude04\ud83d\ude04\ud83d\ude04\ud83d\ude04\ud83d\ude04\ud83d\ude04

these type of characters.


Solution

  • Well if you want to match emojis in the format \uXXXX using Regex, you can use this Regex:

    /\\u[a-z0-9]{4}/gi
    

    This is a simple Demo:

    const regex = /\\u[a-z0-9]{4}/gi;
    const str = `This is a pragraph \\ud83d having  some emojis like these ones:
    
    \\ude04
    
    \\ud83d
    
    \\ude04
    
    Have you seen them?
    
    \\ud83d\\ude04
    
    Great!
    
    `;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    The regex you wrote won't work because you were not escaping the \.