user4209821
user4209821

Reputation:

Find specific pattern from var value

i've var object with content inside of it and I want to find to array just the text which look like following pattern

value:function()

the space between it doesnt matter ,

for example for the following text I should get an array [dosomthing,press,click]

doSomething:function()

press : function()


click: function

I need to get an array like

after searching the forum I found some example which doesnt work for me. any idea how to handle it?

var array = (s.indexOf("/\w+:\s*:function") > -1);

Upvotes: 0

Views: 70

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

Use a positive lookahead to match the word characters which are followed by the string :function

> s = 'doSomething:function()\npress : function()\n\nclick: function'
> s.match(/\w+(?=\s*:\s*function)/g)
[ 'doSomething', 'press', 'click' ]

Explanation:

\w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                         more times)
(?=                      look ahead to see if there is:
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                           or more times)
  :                        ':'
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                           or more times)
  function                 'function'
)                        end of look-ahead

Upvotes: 1

Scimonster
Scimonster

Reputation: 33399

It looks like you posted a malformed object. If we correct the code..

{
    doSomething:function() {},
    press : function(){}, 
    click: function(){}
}

...we can use Object.keys() to extract its keys, and then filter them by only methods.

var myObject = {
    doSomething: function(){},
    press: function(){},
    click: function(){},
    someOtherProperty: 5
};

var keys = Object.keys(myObject);

var methods = keys.filter(function(key){
    return typeof myObject[key] == 'function';
});

The variable methods will be ['doSomething', 'press', 'click'].

Upvotes: 0

Related Questions