Matthew
Matthew

Reputation: 2246

RegExp "g" flag not replacing every instance

I'm working on an EM to PX converter. Basically you paste in your code in the "PX" textarea, and then the same code will appear in the "EM" textarea with em values. It kinda works, but doesn't replace the value of all instances. For example: If you type "padding: 5px;" it will give you "padding: 0.313em;" successfully. However... if you put in "padding: 5px 4px;" it only replaces the "px" to "em" not the actual number values.

Try it out for yourself here :: http://jsfiddle.net/tJsNz/

        function pxToEm(){
        var px = document.getElementById("px"),
            em = document.getElementById("em"),
            parent = document.getElementById("parent-font-size");

        var pxVal = px.value.match(/\d+/ig);
        var pxToEm = 1 / parent.value * pxVal;
        var pxToEmFixed = pxToEm.toFixed(3);
        var pxToEmAnswer = px.value.replace(pxVal, pxToEmFixed).replace(/px/ig, "em");

        em.value = pxToEmAnswer;
    }

Upvotes: 2

Views: 122

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276406

Consider using .replace with a callback function. I think this is what you want - To find every match and replace based on it.

String's .replace method can accept a callback as a second parameter, and run that callback on every matches. You can run it and match all numbers then replace them with their translation value.

For a simpler example

var i=0;
"aaaaaa".replace(/a/g,function(match){
    return i++;
});

Will return "012345". Here is another example from MDN

In your case something like:

var pxToEmAnswer = px.value.replace(/\d+/ig, function(match){
    return 1 / parent.value * match;
}).replace(/px/ig, "em");

(fiddle)

Upvotes: 6

Related Questions