Igor Simic
3 years ago

HTML entities filter in Angular - decode or encode


How to convert “ to double quotes using angularjs? If, for example you have to set title meta tag using angularjs and title string contains double quotes encoded using  HTML entity then we need to create custom filter which will convert this data back to readable format.

Here we have two filters, from HTML entities and to HTML entities

app.filter('fromHtmlEntities',function(){

	return function(string){
		return (string+"").replace(/&#\d+;/gm,function(s) {
	        return String.fromCharCode(s.match(/\d+/gm)[0]);
	    })
		
	}

});

app.filter('toHtmlEntities',function(){
	return function(string){

		return string.replace(/./gm, function(s) {
		        return "&#" + s.charCodeAt(0) + ";";
		    });
		
	}

});
So, if the value of tagData.title is Joanna “The Champion” Jedrzejczyk
// do not forget to include $filter in your controller dependecies
console.log(  $filter('fromHtmlEntities')(tagData.title) ); // output will be Joanna: “The Champion” Jedrzejczyk
console.log( $filter('toHtmlEntities')(tagData.title) ); //  output will be:Joanna &#8220&#59;The Champion&#8221&#59; Jedrzejczyk – enjoying the vacation