Sol
Sol

Reputation: 1029

How can you strip html tags then limit the amount of characters shown in JQuery?

How can you strip html tags then limit the amount of characters shown after stripping the tags? I figured out how to do one or the other, but not stripping the tags then limiting the characters shown.

var txt = "<div>dasda</div>";
$('#modalload').html(txt).text().substr(0, 2);

so in this example it should show "da" instead of showing "<d" or having an error.

Upvotes: 0

Views: 180

Answers (3)

sanatsathyan
sanatsathyan

Reputation: 1763

Try this code:

var txt = "<div>dasda</div>";  
$('#modalload').html($(txt).text().substr(0, 2));

This will work if txt variable is a tag.

Upvotes: 1

Sol
Sol

Reputation: 1029

$('#modalload').html(txt).text(function(index, currentText) {
    return currentText.substr(0, 2);
});

Upvotes: 0

tenshi
tenshi

Reputation: 56

You can use regular expression to remove html tags from the text first.

$('#modalload').html(txt2).text()
  .replace(/<[^>]+>/g, '')
  .substr(0, 2);

Upvotes: 1

Related Questions