Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject some string to a specific part of string in C#

How to insert some string to a specific part of another string. What i am trying to achieve is i have an html string like this in my variable say string stringContent;

 <html><head>
 <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
 <meta name="Viewport" content="width=320; user-scaleable=no; 
 initial-scale=1.0">
 <style type="text/css"> 
 body {
       background: black;
       color: #80c0c0; 
 } 
 </style>
 <script>

</script>
</head>
<body>
<button type="button" onclick="callNative();">Call to Native 
Code!</button>

<br><br>
</body></html>

I need to add below string content inside <script> <script/> tag

    function callNative()
{
    window.external.notify("Uulalaa!");
}
    function addToBody(text)
{
    document.body.innerHTML = document.body.innerHTML + "<br>" + text;
}

How i can achieve this in C#.

like image 684
StezPet Avatar asked May 31 '13 11:05

StezPet


2 Answers

Assuming your content is stored in the string content, you can start by finding the script tag with:

int scriptpos = content.IndexOf("<script");

Then to get past the end of the script tag:

scriptpos = content.IndexOf(">", scriptpos) + 1;

And finally to insert your new content:

content = content.Insert(scriptpos, newContent);

This at least allows for potential attributes in the script tag.

like image 86
James Holderness Avatar answered Oct 27 '22 10:10

James Holderness


Use htmlString.Replace(what, with)

var htmlString = "you html bla bla where's the script tag? oooups here it is!!!<script></script>";

var yourScript = "alert('HA-HA-HA!!!')";

htmlString = htmlString.Replace("<script>", "<script>" + yourScript);

Note that this will insert yourScript inside all <script> elements.

like image 20
Ahmed KRAIEM Avatar answered Oct 27 '22 11:10

Ahmed KRAIEM