JavaScript match with RegEx

The JavaScript match() function can be really useful when trying to match certain parts of a string. For example, if one were to use window.getComputedStyle() to get a color from a DOM Node, Chrome will return an RGB value. However, you may need to have the RGB as Object in the following format

var computedRgb = {  
 r: 59,
 g: 34,
 b: 12
}

To archive this, you can check use String.prototype.match. Based on the provided RegEx or String, match() will return an array of occurences inside the String it is used on.

Consider having a String with Numbers inside that are absolutley wrong here.

var str = 'I have some 123 numbers 245 inside 12 that do not belong 1234556 here.'  

With match and the RegEx \d (digit) parameter, we can find these numbers and then replace() them! The d needs to be escaped because otherwise the real d character would be matched. The + after \d within the RegEx is used to match one or more digits.

// numbs will be an array containing the found numbers.
var numbs = str.match(/\d+/g);  

So now we've got an Array containing all numbers that appear inside the string. Using replace we can now replace all numbers with an empty string (which removes them) by using Array.forEach

numbs.forEach(function(number) {  
    str = str.replace(number, '');
});

Below is a working example created on CodePen.

See the Pen Matching Numbers with RegEx and String.match() by Kevin Gimbel (@kevingimbel) on CodePen.

Using this technique, transform a string (as rgb(59, 34, 12) into an Object becomes pretty simple.

function transformRgbToObj(string) {  
var finds = string.match(/\d+/);  
 return {
     r: finds[0],
     g: finds[1],
     b: finds[2]
 }
}

// usage
var bg = window.getComputedStyle(SomeDomNode)['background-color'];  
var myRgb = transformRgbToObj(bg);  

myRgb now holds the returned Object and the single color values are accessable via myRgb.r,myRgb.g and myRgb.b.