user2338652
user2338652

Reputation: 467

How to replace part of a text using regular expression in JavaScript?

I am fetching HTML content from database and displaying in UI. If the displayed content contains images having width and height specified then I need to replace the image width and height to some fixed value while displaying in UI.

One sample content is 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, I want to set the image width=300 and remove the height dynamically for different images.

I have tried to replace the text using regular expression as follows:

.replace(new RegExp("width=([^&]{0,})", 'gi'), 'width=300') 
.replace(new RegExp("[?&]height=([^&]{0,})", 'gi'), '')

But it gives result as follows:

<p>Sample paragraph text. <br /> <img src="http://www.example.com/myimage.jpg?width=300

It replaces all the text after ?width=300.

I want the 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, I guess, the problem is in the regular expression. Please help me to correct this.

Many many thanks in advance!

Upvotes: 2

Views: 195

Answers (2)

David Hellsing
David Hellsing

Reputation: 108500

Unless you have more parameters in the query, this should do it:

.replace(/(\?width=)[^"]+/i, '$1300');

Put this in a console to test it:

"http://www.example.com/myimage.jpg?width=500&height=500".replace(/(\?width=)[^"]+/i, '$1300');

Upvotes: 0

Matt
Matt

Reputation: 20786

This pattern: /[^&]{0,}/ is gobbling up everything that is not a & character, which is why it extends beyond the URL itself. Instead, since you know that the width and height are numbers, you can just match on digits:

.replace(/\bwidth=\d*/gi,'width=300')
.replace(/&height=\d*|\bheight=\d*&?/gi,'');

The \b is a zero-width match to a word boundary, so that if you have framewidth=500 for example it won't be affected. The 2 matches to height are so that it won't replace both &'s if they are on each side. E.g. you don't want '?width=500&height=500&cache=123' to turn into '?width=300cache=123' for instance.

Upvotes: 1

Related Questions