How to convert a pixel value to a number value using JavaScript ?
The task is to convert the string value containing ‘px’ to the Integer Value with the help of JavaScript. Here, Few approaches are discussed.
Approach 1:
- Use parseInt() method which takes string as first argument and return the Integer value.
Example 1: This example uses approach as discussed above
<!DOCTYPE HTML> < html > < head > < title > Convert a pixel value to a number value using JavaScript. </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var n = el_up.style.fontSize; el_up.innerHTML = "Click on the button to get the number value "+ "from pixel value.< br >Pixel Value - '" + n + "'"; function GFG_Fun() { el_down.innerHTML = "Integer value is " + parseInt(n, 10); } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Approach 2:
- Use RegExp which replaces the ‘px’ by empty string and then convert the result to Integer using Number().
Example 2: This example uses approach as discussed above.
<!DOCTYPE HTML> < html > < head > < title > Convert a pixel value to a number value using JavaScript. </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var n = el_up.style.fontSize; el_up.innerHTML = "Click on the button to get the "+ "number value from pixel value.< br >Pixel Value - '" + n + "'"; function GFG_Fun() { el_down.innerHTML = "Integer value is " + Number(n.replace(/px$/, '')); } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: