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#.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With