开发者

JavaScript: replace a set of characters with another one

I have a multidimentional array composed of latin and Berber strings that I want to use as a reference to replace input data:

var alphabet = Array (  Array( 'a', 'ⴰ' ), Array( 'b', 'ⴱ' ), Array( 'g', 'ⴳ' ), Array( 'gw', 'ⴳⵯ' ), Array( 'd', 'ⴷ' ), Array( 'ḍ', 'ⴹ' ), Array( 'e', 'ⴻ' ), Array( 'f', 'ⴼ' ), Array( 'k', 'ⴽ' ), Array( 'kw', 'ⴽⵯ' ), Array( 'h', 'ⵀ' ), Array( 'ḥ', 'ⵃ' ), Array( 'ɛ', 'ⵄ' ), Array( 'x', 'ⵅ' ), Array( 'q', 'ⵇ' ), Array( 'i', 'ⵉ' ), Array( 'j', 'ⵊ' ), Array( 'l', 'ⵍ' ), Array( 'm', 'ⵎ' ), Array( 'n', 'ⵏ' ), Array( 'u', 'ⵓ' ), Array( 'r', 'ⵔ' ), Array( 'ṛ', 'ⵕ' ), Array( 'ɣ', 'ⵖ' ), Array( 's', 'ⵙ' ), Array( 'ṣ', 'ⵚ' ), Array( 'c', 'ⵛ' ), Array( 't', 'ⵜ' ), Array( 'ṭ', 'ⵟ' ), Array( 'w', 'ⵡ' ), Array( 'Y', 'ⵢ' ), Array( 'z', 'ⵣ' ), Array( 'ẓ', 'ⵥ' ) );                    

var word = $("input[name=word]").val();

var word_split = word.split("");

var tifinaghized = '';

for (var i = 0; i < word_split.length; i++)
{
    tifinaghized += word.replace(word_split, alphabet[i][1]);
}

$("span.generated_tifinaghe").html( tifinaghized );

So if the user types "a" it should be replaced by the berber representation of it "ⴰ". This replaces only the first character but not the whole input data. How could I replace the Latin characters in the alphabet array wit开发者_StackOverflowh their pairs on the same alphabet array?

PS; if you see squares it's normal.


You need to use a regular expression with the global option set to replace all of the instances. But, you can also simplify this code a bit and get rid of the loop. Instead of Arrays, use an object:

var alphabet = {
    'a': 'ⴰ',
    'b': 'ⴱ',
    'g': 'ⴳ',
    'gw': 'ⴳⵯ',
    'd': 'ⴷ',
    'ḍ': 'ⴹ',
    ...
    'z': 'ⵣ',
    'ẓ': 'ⵥ'
};

Then use a regular expression with a replacement function:

var word = $("input[name=word]").val();
var tifinaghized = word.replace(/[abgdḍefkhḥɛxqijlmnurṛɣsṣctṭwYzẓ]|gw|kw/g, function(s) {
    return alphabet[s];
});

Working demo: http://jsfiddle.net/gilly3/MdF6R/


If you change:

 tifinaghized += word.replace(word_split, alphabet[i][1]);

to use regular expressions:

 tifinaghized += word.replace(new RegExp(word_split, 'g'), alphabet[i][1]);

the g will find all occurrences.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜