1

Suppose I have a string which contains an HTML file. How do I get the script part only as my sub string?

The example string is :

str="<html>...<script>...</script>...</html>"

I only need the script part.

<script type = "text/javascript">
function Showques()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    } 
    else 
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    //getting response from servlet
    xmlhttp.onreadystatechange=function();
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) 
        {
            var localString=xmlhttp.responseText;
            var locationstart =localString.indexOf('<script>');
            var locationend = localString.indexOf('</script>');
            //eval(xmlhttp.responseText);
            document.getElementById("ques").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","XmlApp",true);
    xmlhttp.send();
}
</script>

When I give </script> within indexOf method it's considering as the end of my script which i declared in the beginning and rest of things I am getting error.

3 Answers 3

2

Use

string.indexOf(searchstring, start)

to find the proper index in the string. You can then use the index in your substr function.

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

my string looks like this: str="<html>...<script>...</script>...</html>, i need the script part alone.
1

you should probably better use a dom parser if your string is an actual html file.
If you are working with javascript, here is a simple jQuery way to do it :

str="<html>...<script>...</script>...</html>";
$(str).find("script").get(0).outerHtml;

Comments

0

try this from aNd This

 String str = "yourStringTosearch"
 int location = str.indexOf('String');
 string.substring(location , to)

Ok according to ur example do this

 String str = "<html>...<script>...</script>...</html>"
 int locationStart = str.indexOf('<script>');
 int locationend = str.indexOf('</script>');
 strinf finalString =string.substring(locationStart , locationend );   //ur final string value

3 Comments

my string looks like this: str="<html>...<script>...</script>...</html>, i need the script part alone.
<script type = "text/javascript">
@user1101422 : this was the output ? <script type = "text/javascript">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.