Search code examples
javascriptregexstringreplaceeval

do calculation on numbers in text using regex


I have an html file with multiple paragraphs, each one has a top and left tag that is in px. I'm trying to translate this numbers to percent using regex. my page width and height is 500px and 1000px respectivly. For example for this text:

<p "position:absolute;left:200px;top:200px"></p>

I want the result to be:

<p "position:absolute;left:40%;top:20%"></p>

Solution

  • You can capture patterns via regex but cannot have computation done through them.

    In your case you could use a regex like

    <p.*left:(\d{1,3})px;top:(\d{1,3}).*p>
    

    This regex will spit out 2 matches which would the captured numbers. You can now convert them and replace using the captured group number.

    Or you could simply use a callback to replace method

    str = '<p "position:absolute;left:200px;top:200px"></p>';
    pattern = /\d+/g;
    function replacer(match) {
    	match = (match/500)*100 + '%';
      return match;
    }
    str = str.replace(pattern, replacer);
    str = str.replace(/px/g, '');
    console.log(str);