bobbyrne01
bobbyrne01

Reputation: 6743

Using javascript's replace with wildcard to change width attribute inside string

I'm trying to use .replace('width=".*"', 'width="100"'), since width could be anything in the original string. But at the moment that does not change anything.

https://jsfiddle.net/bobbyrne01/8p404z5t/

html

<div id="1"></div><br/>
<div id="2"></div>

javascript

var fullURL = '<iframe class="embedly-embed" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fi.imgur.com%2F…key=2aa3c4d5f3de4f5b9120b660ad850dc9&amp;type=video%2Fmp4&amp;schema=imgur" width="406" height="720" scrolling="no" frameborder="0" allowfullscreen&gt;&lt;/iframe>';

document.getElementById('1').textContent = fullURL;

var moddedURL = fullURL.replace('width=".*"', 'width="100"');
document.getElementById('2').textContent = moddedURL;

result ..

<iframe class="embedly-embed" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fi.imgur.com%2F…key=2aa3c4d5f3de4f5b9120b660ad850dc9&amp;type=video%2Fmp4&amp;schema=imgur" width="406" height="720" scrolling="no" frameborder="0" allowfullscreen&gt;&lt;/iframe>

<iframe class="embedly-embed" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fi.imgur.com%2F…key=2aa3c4d5f3de4f5b9120b660ad850dc9&amp;type=video%2Fmp4&amp;schema=imgur" width="406" height="720" scrolling="no" frameborder="0" allowfullscreen&gt;&lt;/iframe>

Upvotes: 3

Views: 3349

Answers (1)

thefourtheye
thefourtheye

Reputation: 239613

If you need to use wildcards, then you need to use Regular Expression, like this

var moddedURL = fullURL.replace(/width=".*?"/, 'width="100"');

Here, we use /width=".*?"/, which is a Regular Expression, and it means that match any string of the pattern width=" followed any character which occurs zero or more times, till we see the first ".

Note: .* is actually greedy. If we don't use ? after that, it will match everything in the string till the last ". That is why we explicitly make it non-greedy by using ? and it will stop matching at the first occurrence of " following it.


In fact, you know that it will be numbers only. So you can make it match strictly like this

var moddedURL = fullURL.replace(/width="\d*"/, 'width="100"');

Now, it will match zero or more numeric digits, instead of any characters. Now we don't use ? modifier because, the moment it finds a character which is not a digit, RegEx engine will stop matching. So we don't have to worry much about greedy matching here, unless your string will have whitespaces around the number.

Upvotes: 8

Related Questions