4

I'm trying to build a website using jquery-1.10.2 where I want to replace css related strings like <style>, <link> etc. with comment string <!-- -->.So far I've managed to replace them by <!-- but I can't find a way to add --> by regex since I'm noob about regex. Here are my codes,

$(document).ready(function () {
$('#btnUpdate').click(function () {
    $('#divText').val($('#divText').val().replace(/<\/?style.*?>|<\/?link.*?>/, "<!--"));
});

});

JSFiddle Demo

How can I add --> after the last string? Need this help badly. Thanks.

1
  • What's your expected output? Commented Jun 16, 2015 at 10:42

3 Answers 3

2

Use capturing groups.

$('#divText').val($('#divText').val().replace(/(<\/?(?:style|link).*?>)/, "<!-- $1 -->"));

OR

$('#divText').val($('#divText').val().replace(/(<\/?(?:style|link)[^>]*>)/, "<!-- $1 -->"));

DEMO

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

1 Comment

You might want to add an optional ending space or / in case non-HTML 5 is used.
1

Not a fan of using regex to modify html content, so

$(document).ready(function() {
  $('#btnUpdate').click(function() {
    var $tmp = $('<div />', {
      html: $('#divText').val()
    });

    $tmp.find('link, style').replaceWith(function() {
      return document.createComment(this.outerHTML);
    });

    $('#divText').val($tmp.html());
  });
});

$(document).ready(function() {
  $('#btnUpdate').click(function() {
    var $tmp = $('<div />', {
      html: $('#divText').val()
    });

    $tmp.find('link, style').replaceWith(function() {
      return document.createComment(this.outerHTML);
    });

    $('#divText').val($tmp.html());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="divText" style="width: 400px; height: 300px;">
  something

  <link href="//abc.comd/ss.css" rel="stylesheet"/>

  <style>
    div: {color: red;}
  </style>

  <div>adf</div>
</textarea>
<br>
<button id="btnUpdate">Update</button>

1 Comment

I thought the goal was to actually remove the tags, but apparently that's not the case. I didn't know about createComment, so that's nice. +1
0

Why dont you just try to remove those attributes with removeAttr?

$(document).ready(function () {
$('#btnUpdate').click(function () {
    $('#divText').val($('#divText').removeAttr("style");
});

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.