I'm trying to edit image size (width & height) in the string variable but I need to edit it by Regex expression to take its width and height and then divide it by 2.
In Example:
I have images in a string variable
const html = `<p><img alt="" src="https://media.cheggcdn.com/media/1cb/1cb8a6aa-8dbf-4cc1-90ae-e214d46eb4c1/php7FkMW8.png"style="height:34px;width:158px;" /></p><p><strong>explanation:</strong></p><p><strong><img alt="" src="https://media.cheggcdn.com/media/7f8/7f87506b-9fb5-421f-85e6-b283732266d2/phprAsgze.png"style="height:130px;width:387px;" /></strong></p>`
As you can see, there are two img tags in this variable.
The first image size is: (height:34px;width:158px;)
.
The second image size is: height:130px;width:387px;
.
Now, I need to edit the first and the second image size to take its half size
Example to edit 34px height: 34/2 = 17 and the same for the width...
So, the new size of height is: 17px then replace the new size with its CSS style
The final result should be like this:
const HTMl = `<p><img alt="" src="https://media.cheggcdn.com/media/1cb/1cb8a6aa-8dbf-4cc1-90ae-e214d46eb4c1/php7FkMW8.png"style="height:17px;width:79px;" /></p><p><strong>explanation:</strong></p><p><strong><img alt="" src="https://media.cheggcdn.com/media/7f8/7f87506b-9fb5-421f-85e6-b283732266d2/phprAsgze.png"style="height:65px;width:193.5px;" /></strong></p>`
i hope it's clear what i need. you can do it by regex or any method that can do what i need. Thanks!
CodePudding user response:
Before set it to const HTMl
variable, you can create variables for the height and width of the imgs.
const firstImgWidth = 158;
const secondImgWidth = 387;
const firstImgHeight = 34;
const secondImgHeight = 130;
Then you can interpolate these variables with Template Strings, see documentation
const html = `<p><img alt="" src="https://media.cheggcdn.com/media/1cb/1cb8a6aa-8dbf-4cc1-90ae-e214d46eb4c1/php7FkMW8.png"style="height:${firstImgHeight}px;width:${firstImgWidth}px;" /></p><p><strong>explanation:</strong></p><p><strong><img alt="" src="https://media.cheggcdn.com/media/7f8/7f87506b-9fb5-421f-85e6-b283732266d2/phprAsgze.png"style="height:${secondImgHeight}px;width:${secondImgWidth}px;" /></strong></p>
This way, you will be able to manipulate your <imgs>
attributes easily.
CodePudding user response:
If it’s possible you should look at the document objects rich functionality. MDN has some good documentation on it. A good document property to start with is document.createElement
.