Home > Enterprise >  How to match a whole word or sentence after a specific character with regexp
How to match a whole word or sentence after a specific character with regexp

Time:05-09

I have an object that contains other objects, some of these have a key that is a string that starts with column like this: ':Campaign':{data} I need to loop through that object and save all the keys that start with column (:) into strings. For that I need a regex that matches the first character : and take the whole word right after :

so far I wrote this but found returns only the column:

const keys = Object.keys(output)
const regex = /^:*/gi;

keys.forEach(key =>  {
  const found = key.match(regex);
  console.log('found: ', found);
})

Log is:

found:  [ ':' ]
found:  [ ':' ]

CodePudding user response:

Here are 2 options depending on whether you want to include the colon in the pattern that you are capturing.

  • with the colon ^:\w*
  • with a lookback for the colon (?<=^:)\w*
    This will match a word after the colon.
    You may want any number of any character .* or any combination of word characters and spaces `[\w\s]*

CodePudding user response:

Try this !

[':].*[']

It should give you the whole key in single quotes.

  • Related