从元素中删除(软连字符)实体

时间:2015-12-02 12:41:49

标签: jquery html css html-entities

我正在尝试从我的元素

中删除所有­个实体(软连字符)

我一直在尝试使用jquery来做这件事。 当我从包含实体的html元素中获取文本时,我似乎得到一个字符串,其中实体被“隐藏”或无法编辑。

你是否必须做一些特别的事情来实际获得包含实体的字符串?

$( document ).ready(function(){
  $("button").on("click", function(){
    var html = $("div > span").html();
    var newHtml = html.replace("­", "");
    
    $("div > span").html(newHtml);
  });
});
div{
  max-width: 50px;
  padding: 10px;
  border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>My text will be hyphe&shy;ned</span>
</div>
<button>
  Remove Hyphens
</button>

1 个答案:

答案 0 :(得分:7)

使用正则表达式:

var newHtml = html.replace(/\&shy;/gi, "");

注意:您可能还需要检查&#173;,因为浏览器会将其视为数字,而不是人类友好的字符。

<强>解释

/(\&shy;)/gi
  1st Capturing group (\&shy;)
    \& matches the character & literally
    shy; matches the characters shy; literally (case insensitive)
    g modifier: global. All matches (don't return on first match)
    i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

<强>段

$( document ).ready(function(){
  $("button").on("click", function(){
    var html = $("div > span").html();
    var newHtml = html.replace(/(\&shy;|­|&#173;)/gi, "");
    
    $("div > span").html(newHtml);
  });
});
div{
  max-width: 50px;
  padding: 10px;
  border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>My text will be hyphe&shy;ned</span>
</div>
<button>
  Remove Hyphens
</button>

Regex101:https://regex101.com/r/wD3oX7/1