Clean and shy; (soft hyphen) from an element

I am trying to delete all ­ entities (soft hyphens) from my element,

I am trying to do this using jquery. When I extract the text from the html element containing the object, I seem to get a line where the object is "hidden" or cannot be edited.

Do you need to do something to actually get a string that includes entities?

 $( 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
source share
1 answer

Use regex:

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

Note. You may also need to check &#173; , because the browser processes it in numbers, and not in friendly human characters.

Explanation:

 /(\&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]) 

Excerpt

 $( 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

+6
source

All Articles