DaveKingsnorth
DaveKingsnorth

Reputation: 165

Search and replace multiple special characters with jquery

Currently this will take the text from the textarea and replace all the characters that are specified in the charMap:

<form>
<textarea name="text" id="text" style="width:300px; height:200px;"></textarea><br />
<input type="button" name="submit" id="submit" value="submit" />
</form>

var charMap = {
    "Å":'x',
    "å":'y',
    "b":'z',
    "c":'f'
};

$('#submit').click(function() {

    var str = $('#text').val();
    var str_array = str.split('');

    for( var i = 0, len = str_array.length; i < len; i++ ) {
        str_array[ i ] = charMap[ str_array[ i ] ] || str_array[ i ];
    }

    foo = str_array.join('');
    $('#text').val(foo);

});

The problem is that it does not recognise the special characters. So it will replace 'b' and 'c' but not 'Å' and 'å'.

Any ideas?

Upvotes: 4

Views: 5242

Answers (3)

Carvill
Carvill

Reputation: 1

Your original code is correct, however the problem is due to the charset of the page, try the following:

  1. Make sure your page is saved as UTF-8
  2. Include the following in your header

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

I was head scratching with the same problem, this resolved my issue.

Upvotes: 0

user113716
user113716

Reputation: 322462

Now that I'm understanding the requirements better, you can just create a map of characters to replacements like this:

Example: http://jsfiddle.net/gaG28/2/

var charMap = {
    a:'z',b:'v',c:'n',d:'s',e:'d',
    f:'k',g:'e',h:'y',i:'j',j:'r',
    k:'f',l:'m',m:'a',n:'c',o:'q',
    p:'t',q:'g',r:'i',s:'b',t:'p',
    u:'l',v:'u',w:'h',x:'o',y:'w',z:'x'
};
var str = "abcdefghijklmnopqrstuvwxyz";

var str_array = str.split('');

for( var i = 0, len = str_array.length; i < len; i++ ) {
    str_array[ i ] = charMap[ str_array[ i ] ] || str_array[ i ];
}
str = str_array.join('');

This will also leave any characters alone that are not found in the map.

Upvotes: 2

Alex
Alex

Reputation: 65944

Since .replace() acts on a string, and returns a string, you can chain multiple replace calls together:

var text = $(this).val().replace(/a/g, "z").replace(/b/g, "y").replace(/c/g, "x");

Upvotes: 2

Related Questions