Finding and replacing multiple special characters with jquery

Currently, it will take the text from the text field and replace all characters specified in 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 recognize special characters. Therefore, it will replace "b" and "c", but not "& Aring"; and '& aring;'.

Any ideas?

+4
source share
3 answers

Now that I have a better understanding of the requirements, you can simply create a character map for such notes:

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(''); 

It will also leave any characters that are not found on the map.

+2
source

Since .replace() acts on a string and returns a string, you can bind several replacement calls together:

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

The source code is correct, but the problem is with the encoding of the page, try the following:

  • Make sure your page is saved as UTF-8
  • Include the following in your headline:

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

I ran into the same problem and this solved my problem.

0
source

All Articles