regex - How to replace part of a text using regular expression in JavaScript? -
i fetching html content database , displaying in ui. if displayed content contains images having width , height specified need replace image width , height fixed value while displaying in ui.
one sample content like:
<p> sample paragraph text. <br /> <img src="http://www.example.com/myimage.jpg?width=500&height=500" title="test image" /> sample text. <br /> </p>
here, want set image width=300 , remove height dynamically different images.
i have tried replace text using regular expression follows:
.replace(new regexp("width=([^&]{0,})", 'gi'), 'width=300') .replace(new regexp("[?&]height=([^&]{0,})", 'gi'), '')
but gives result follows:
<p>sample paragraph text. <br /> <img src="http://www.example.com/myimage.jpg?width=300
it replaces text after ?width=300.
i want result like: <p>sample paragraph text. <br /> <img src="http://www.example.com/myimage.jpg?width=300" title="test image" /> sample text.<br /></p>
so, guess, problem in regular expression. please me correct this.
many many in advance!
this pattern: /[^&]{0,}/
gobbling not & character, why extends beyond url itself. instead, since know width , height numbers, can match on digits:
.replace(/\bwidth=\d*/gi,'width=300') .replace(/&height=\d*|\bheight=\d*&?/gi,'');
the \b
zero-width match word boundary, if have framewidth=500 example won't affected. 2 matches height won't replace both &'s if on each side. e.g. don't want '?width=500&height=500&cache=123' turn '?width=300cache=123' instance.
Comments
Post a Comment