2

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 with their pairs on the same alphabet array?

PS; if you see squares it's normal.

2 Answers 2

13

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.