Matthew
Matthew

Reputation: 2246

JavaScript switch with variable?

I want to check if a string has a certain letter, and then remove said letter.

jsFiddle — http://jsfiddle.net/nNb5S/6/

For example, if you type...

.. in the "input" textarea, the "result" should return...

I already figured it out, but I was wondering if it could be done via Switch?

This is my working code ::

function doSomething() {

var input = document.getElementById("h"),
    result = document.getElementById("m");

var x = /x/gi;
var y = /y/gi;
var z = /z/gi;

if(input.value.indexOf(x)) {
    result.value = input.value.replace(x,"");        
}
if(input.value.indexOf(y)) {
    result.value = result.value.replace(y,"");        
}
if(input.value.indexOf(z)) {
    result.value = result.value.replace(z,"");        
}

}

This is my switch code :: This below code ONLY works when arg is defined; but, I don't want to define it.

function doSomething() {

var input = document.getElementById("h"),
    result = document.getElementById("m");

var x = /x/gi;
var y = /y/gi;
var z = /z/gi;

/*arg = x;*/ // ONLY WORKS WHEN YOU DEFINE arg.  HOW DO YOU DEFINE arg AS ANY OF THE VARIABLES?

var iO = input.value.indexOf(arg);

switch (arg) {

    case x:
        result.value = input.value.replace(x, "");
    break;
    case y:
        result.value = result.value.replace(y, "");
    break;
    case z:
        result.value = result.value.replace(z, "");
    break;

}
}

Upvotes: 0

Views: 100

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149040

A switch statement is definitely not the way to go. A much better option would be to use a single regular expression replacement like this:

function doSomething() {
    var input = document.getElementById("h"),
        result = document.getElementById("m");
    result.value = input.value.replace(/[xyz]/gi, "");
}

Demonstration

But since you're already using jQuery, this can be simplified even more:

function doSomething() {
    $("#m").val($("#h").val().replace(/[xyz]/gi, ""));
}

Demonstration

Upvotes: 3

Ry-
Ry-

Reputation: 225054

indexOf is not how you match regular expressions. Neither is switch. You’d normally use RegExp.prototype.test as follows:

if (x.test(input.value)) {
    result.value = input.value.replace(x,"");        
}

but seeing as you’re performing replacements, isn’t this more appropriate?

result.value = input.value
    .replace(x, '')
    .replace(y, '')
    .replace(z, '');

? Unless you really only want to replace matches of the last regular expression of the three that matches.

Upvotes: 1

Related Questions