Search code examples
javascripttextreplaceonkeypress

Javascript for replacing an abreviation by his equivalent


I met some trouble with a javascript.

In fact I have in my database many records that are abreviations and ther equivalent,

for example, replace tel => telephone etc...

So I have this function

$('#tags').keyup(function(e){
    var code = e.which ? e.which : e.keyCode;
     console.log(code);
    if (code == 'tel'){
        var input = this.value;
        input = input.substr(0, input.length -1);
        console.log(input);
        input += 'tel';
        this.value = input;        
    }

});

Actualy this does not work the trouble is that I do not have aby mistakes in the console of javascript.

Anykind of help will be much appreciated.

Kind regards.

SP.


Solution

  • This should work:

    $('#tags').keyup(function(e){
        var code = e.which ? e.which : e.keyCode;
        var input = this.value;
        if (input.indexOf('tel') != -1) {
           this.value = this.value.replace(/\btel\b/gi,'telephone');
    
        }
    
    });
    

    Here is a fiddle