Reputation: 21
I'm trying to remove '
from my string. How to do that? I'm using ajax with JSON.
My code looks like this:
<html>
<body>
<p id="testHTML"></p>
</body>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$.getJSON("IOCounter.html", function(data) {
$('#testHTML').text(data.testHTML);
});
}, 2000); //Refreshrate in ms
});
</script>
</html>
Inside testHTML, I get the string "HelloWorld" from IOCounter.html but when I display it inside index.html I get:
'HelloWorld'
Now I just want to remove '
to get only HelloWorld. What do I have to do?
Upvotes: 0
Views: 7427
Reputation: 1145
You can decode the Unicode characters with this function :
export const unicodeDecode = (text: string) => {
const decoded = text.replace(/&#x([0-9a-f]+);/gi, (_, code) =>
String.fromCharCode(parseInt(code, 16))
);
return decoded;
};
It will replace all #...;
like '
by the Unicode characters.
In the callback function of replace, we take the code (for '
its 27
) and we replace it by its UTF value using String.fromCharCode(parseInt(code, 16))
Alternatively, in a Node.js application, you can use node-html-parser !
Found in this answer
import { parse } from 'node-html-parser';
const root = parse('<ul id="list"><li>Hello World</li></ul>');
console.log(root.querySelector('#list'));
function htmlDecode(str) {
const doc = new DOMParser().parseFromString(str, "text/html");
return doc.documentElement.textContent;
}
But in all case, the homemade solution will work.
Upvotes: 0
Reputation: 769
The string returned is HTML encoded. To get a plain text string, it needs to be decoded.
DOMParser (supported in most browsers) can be used to decode the string as follows:
function htmlDecode(str) {
const doc = new DOMParser().parseFromString(str, "text/html");
return doc.documentElement.textContent;
}
Using this, you can decode the string and then set it to #textHTML
.
$.getJSON("IOCounter.html", function(data) {
$('#testHTML').text(htmlDecode(data.testHTML));
});
Upvotes: 2