Deva Asirvatham Deva Asirvatham - 10 months ago 38
Javascript Question

How to check whether a value using charAt in JavaScript

I am very new to JavaScript. Presently, I am doing a Program where I want to translate a text into "rovarspracket". i.e) Double every consonant and place an occurrence of "o" in between. For ex: , translate("this is fun") should return the string "tothohisos isos fofunon" . I am not able to get the result as desired. Help me that i would learn.

This is my following code which i tried.

<button type="button" onclick="translate('de')">try it</button>
<h2 id="ad" />
function translate(t)
var l=t.length;
var v=["a","e","i","o","u",""];
var b="";
for(var i=0;i<l;i++)
{ //alert(i);exit;
var c=t.charAt[i];alert(c);



Answer Source

I've taken the liberty to simplify the functionality for you:

var str = "this is fun",
    arr = str.split(''); // Split the string into an array of separate characters.
    mapped ={
        if(["a","e","i","o","u"].indexOf(c) == -1) // If the character is a consonant
            return c + 'o' + c; // replace it,
        return c;               // otherwise, just keep the current character.
    result = mapped.join('');   // Rebuild the string


Or, a little more compact:

var str = "this is fun",
    result = str.split('').map(function(c){
        retrun (["a","e","i","o","u"].indexOf(c) == -1) ? (c + 'o' + c) : c;