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?
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.
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");
Your original code is correct, however the problem is due to the charset of the page, try the following:
- Make sure your page is saved as UTF-8
- 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.
精彩评论