Lodder
Lodder

Reputation: 19743

Javascript - Replacing any instance of character in a string

Take the following string:

Lodder

What I'm trying to do is, ensure the above is the result of any alternatives that are written on keypress. Possible alternatives could be something like:

Loader
Lo [a] der
Lo .a der

The alternatives are always based on the letter a replacing the first d in the string

The code I've written so far:

$('#element').keyup(function(e) {

    var Lodder = this.value.replace(/Loader|Lo4der/g, 'Lodder');

    if (Lodder != this.value)
    {
        this.value = Lodder;
    }

});

As you can see, it only replaces exact alternatives, however I'm trying to make it more dynamic by detecting more advanced alternatives.

Is there a more or less simple, but, robust solution to this?

If so, could someone point me in the right direction?

Upvotes: 1

Views: 60

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174874

Use .*? to match any number of characters non-greedily.

value.replace(/\bLo.*?der\b/g, 'Lodder');

\b called word boundary which matches between a word character and a non-word character (vice-versa).

Upvotes: 3

Related Questions