Change specific numbers in a string

I have a string that sometimes contains css font sizes. For example:

str = '<span style="font-size: 200px;white-space:nowrap;">Text</span>
<br><span style="color:#555555;font-size:10px;">Some otherText</span>';

      

I need to change all font sizes by multiplying them by a set factor, for example 1.5

var ratio = 1.5;

      

Finding and replacing is not my strong suit. How do I search for a string for all font sizes and then do math on each number?

So this line with this relationship would become:

str = '<span style="font-size: 300px;white-space:nowrap;">Text</span>
<br><span style="color:#555555;font-size:15px;">Some otherText</span>';

      

+3


source to share


3 answers


Suppose it is like a string and there is no better way (if it came from innerHTML

or so you are doing it wrong) then ...

var fauxDocFrag = document.createElement("div");
var elements, i, len;

fauxDocFrag.innerHTML = str;

elements = fauxDocFrag.getElementsByTagName("*");

for (i = 0, len = elements.length; i < len; i++) {
    elements[i].style.fontSize = (parseInt(elements[i].style.fontSize) * 1.5)
                                 + "px";
}

str = fauxDocFrag.innerHTML;

      

jsFiddle .

If your browser doesn't suck ...



var fauxDocFrag = document.createElement("div");

fauxDocFrag.innerHTML = str;

[].forEach.call(fauxDocFrag.getElementsByTagName("*"), function(element) {
     element.style.fontSize = (parseInt(elements.style.fontSize) * 1.5)
                              + "px";
});

str = fauxDocFrag.innerHTML;

      

If any of the ads were missing in the attribute style

, you can use getComputedStyle()

.

I didn't use the real documentFragment

one because it doesn't support the property innerHTML

.

+3


source


Alex is right, perhaps a much better way, but to answer your question with a line replacing the answer:



str = str.replace(/(\d+)px/g, function (fullStr, pixels) {
  return (pixels * 1.5) + 'px';
});

      

+1


source


You can use an replace

object method String

and supply a function as the replacement value.

str.replace(/font-size:\s*(\d*)/g,
            function (line, p1) { return ratio * parseInt(p1) })

      

0


source







All Articles