Javascript替换技巧

时间:2016-05-11 06:47:29

标签: javascript jquery

我正在使用像这样的JavaScript字符串组合

class B

我必须找到无效的标签(没有结束标签),例如str = "<div>xyz 123 <rd> </div>" or str = "sample text <abc>" or str = "Text <input type="text" /> new value <bla> ." ,并且需要替换为(<rd>, <abc>, <bla>)

有人可以帮忙解决这个问题。完全使用JavaScript。

1 个答案:

答案 0 :(得分:1)

使用jQuery,你可以借助 replace()

来做这样的事情

var str = `<div>xyz 123 <rd> </div>
sample text <abc>
Text <input type="text"/> new value <bla>`;


console.log(
  str.replace(/<([a-z]+)([^>]*[^\/])?>(?![\s\S]*<\/\1)/gi, function(m) {
    return $('<div/>').text(m).html(); // encoding matched text
  })
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Regex explanation here

Regular expression visualization

请参阅以下html编码的答案:HTML-encoding lost when attribute read from input field