4

This code gets html data and should replace all javascript content

$.ajax({
    url: url,
    success: function(data){
        data = data.replace(/<script.*?<\/sc/mg,'');
        alert(data);
    },
    dataType: 'html'
});

But there is stay javascript code in the data

.....</div><!-- end header -->
<div id="snapshot">
    <a href="?cat=<div style=&panel=center" id="leftNav" class="navlink"><i class="icon-previous icon-large white"></i></a>

    <a href="?cat=<div style=&panel=left" id="rightNav" class="navlink"><i class="icon-next icon-large white"></i></a>
<script type="text/javascript">
$(document).ready(function() {
    $('body').append('<div id="loaded_page"></div>');
    url = $('#leftNav').attr('href')
    $.ajax({
        url: url,
        success: function(data){
            data = data.replace(/<script.*?<\/sc/mgi,'');
            alert(data);
        },
        dataType: 'html'
    });

    return;
</script>
    ....................

So I need result to be

.....</div><!-- end header -->
<div id="snapshot">
    <a href="?cat=<div style=&panel=center" id="leftNav" class="navlink"><i class="icon-previous icon-large white"></i></a>

    <a href="?cat=<div style=&panel=left" id="rightNav" class="navlink"><i class="icon-next icon-large white"></i></a>

all javascript should be cut. Regexp data.replace(/<script.*?<\/sc/mg,'') replaces things which are in a one line only

2
  • 1
    and what is the data format you need to regexp? Commented Mar 29, 2012 at 12:53
  • regexp doesn't work, it should replace <script.*?<\/sc with '' Commented Mar 29, 2012 at 12:56

3 Answers 3

3

.* doesn't work in javascript over new lines. Instead use [\s\S]*

Here's the regex:

/<script[\s\S]*?</script>/i
Sign up to request clarification or add additional context in comments.

Comments

0

This is what you are looking for:

var html = "<html><head><script src='http://jquery.js'></script>\n<script src='http://jquery.js'></script></head><body>I m legend</body></html>";
html.replace(/<script.*?<\/script>/gi,'');

This will return :

"<html><head>
</head><body>I m legend</body></html>"

Comments

0

[T]o match a pattern across multiple lines the character set [^] can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

This means you should use the negative empty selection [^] instead of the dot . to match "all characters".

Comments

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.