-2

I have string like this,

var str="<svg width='321' height='987'></svg>";

I want to replace width and height of this string using JavaScript(widht and height is dynamic here). I tried this

str.replace("width='", "width='100%");

But i know this will not work. i dont know how to replace text within specific string in javascript. Output should looks like,

var str="<div width='100%' height='100%'></div>";

Replace should be only for first occurrence within string.

Himanshu Bhardiya
  • 1,047
  • 14
  • 37

1 Answers1

4

Don't try to do regex/string stuff on chunks of HTML. Use the browser to parse it:

var str = "<svg width='321' height='987'></svg>";

var tempWrapper = document.createElement("div");
tempWrapper.innerHTML = str;
tempWrapper.firstChild.setAttribute("width", "100");
tempWrapper.firstChild.setAttribute("height", "100")

console.log(tempWrapper.innerHTML);

document.querySelector(".myPage").innerHTML = tempWrapper.innerHTML;
svg { border: 1px solid red; }
<div class="myPage"></div>
Community
  • 1
  • 1
user3297291
  • 22,592
  • 4
  • 29
  • 45