How to String.match() distinct it ${SOME_TEXT} using Regex

后端 未结 3 1121
轮回少年
轮回少年 2021-01-16 06:26

I need this string:

var x = \'Hi ${name}! How are you? ${name}, you are old! ${name} share with ${other} how do u ${feel}!\'

I need to know

3条回答
  •  梦谈多话
    2021-01-16 06:37

    I need to know using Regex how much distinct ${ANY_THING} exists

    x.match(/\$\{[^\}]+\}/g)
     .sort()
     .filter(function(element, index, array) {
         return index == array.indexOf(element);
     }) // this .filter() filters out the duplicates (since JS lacks of built in
        // unique filtering functions
     .length;
    

    The code above would return 3, as that's how many distinct items are in the x string.

    JSFiddle: http://jsfiddle.net/cae6P/

    PS: It's not possible to do it with regular expression only. You need to filter duplicates using the .filter() solution or some other similar

提交回复
热议问题