2015-12-02 49 views
6

我想從我的元素中刪除所有­實體(軟連字符)刪除­(軟連字符)實體,從元素

我一直在努力做到這一點使用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>

回答

6

使用正則表達式:

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

+1

謝謝。這工作完美:) –