Danny Danny - 3 months ago 8
jQuery Question

Letter replacement

I want to make letters like 'å ä ö' visible. I need to replace these letters with ascii code, I guess.

I have tried jquery and javascript, but it did not work. Look at the following code please:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>


jQuery("#body").html(
jQuery("#body").html().replace('ä', '&aring;')
);


document.body.innerHTML = document.body.innerHTML.replace(/ä/g, '&aring;');



</script>



</head>

<body id="body">

<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item active" href="index.php">Inlägg</a>
</nav>
</div>
</div>

Answer

You can achieve what you want using one of the three methods below.

codepen

JQuery

// using a regex on the first parameter of replace, 
// picks all the 'ä' instead of the first one 
var replaced = $("body").html().replace(/ä/g,'&aring;'); 
$("body").html(replaced);

JavaScript

// using a regex on the first parameter of replace, 
// picks all the 'ä' instead of the first one 
document.body.innerHTML = document.body.innerHTML.replace(/ä/g, '&aring;');

Better Solution

A better alternative to the two previous code sample is to convert your file to the right encoding. In order to do that, make sure you this snippet in the head of you HTML document.

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

If that's not working, you also have to make sure the file is saved with encoding UTF-8. If you're using Notepad++, this is done via Encoding > Encode in UTF-8.

Comments