Search code examples
javascriptpythonregexreplacesequences

how to find number and calculate (change original number) within document


I have a text with numbers:

width: 32px;
height: 11px;
top: 102px;
left: 36px;

width: 32px;
height: 11px;
top: 102px;
left: 104px;

width: 32px;
height: 11px;
top: 102px;
left: 104px;

and I want to find each number in div/file/document and multiply it by 0,25 = to scale sizes down by 25%. And finally round that to whole number (optional). I want to take a short-cut with repetitive task, but get stuck ;)

I will accept any solution in javascript or python ..or anything fast. I have got so far: http://codepen.io/anon/pen/pvyWqb Thanks.


Solution

  • You could use the following function:

    function return_quarter(str) {
      return str.replace(/([0-9]+)/g,function (number) {
        return Math.round(number * .25);
      });
    }
    

    return_quarter('width: 32px; height: 11px; top: 102px; left: 36px;') returns "width: 8px; height: 3px; top: 26px; left: 9px;"

    Edit:

    Looking at your code, you need to catch everything withing the brackets, not the classes themselves. Nested replace it is!

    function return_quarter(str) {
      return str.replace(/(\{[^}]*\})/g,function (innards) {
        console.log(innards)
        return innards.replace(/([0-9]+)/g,function (number) {
          return Math.round(number * .25);
        });
      });
    }
    

    Give that a shot when you have a chance