Lee Jing Yong
Lee Jing Yong

Reputation: 65

Javascript - Removing a specific letter from a string

bcd kinda return " abc abcc" i wanted it to be "abc abcc" Searched online and people are suggesting .split + .join that didnt work too. And saw another post that might help me on removing the extra space : .charAt. The problem is .charAt only look for the letter, it didnt remove it. Any methods to remove it ? Below is my code:

var a = ["Strange abc abcc", "Genuine bcd bcdd", "Genuine dcb dcbb"]

    for(i=0; i< a.length; i++){
        if(a[i].indexOf("Strange") === 0){
            if(a[i].replace("Strange", '') == " abc"){
                console.log("rip")
                var bcd = a[i].replace("Strange", "")
                console.log(bcd)
            }else{
                console.log("succuess lol")
            }
        }
    }

Upvotes: 2

Views: 96

Answers (1)

Djaouad
Djaouad

Reputation: 22776

Use trim() to remove spaces in the back and front of a string:

var a = ["Strange abc abcc", "Genuine bcd bcdd", "Genuine dcb dcbb"]

var r = a[0].replace("Strange", "").trim();
console.log(r);

Alternatively, you can use a RegExp:

var a = ["Strange abc abcc", "Genuine bcd bcdd", "Genuine dcb dcbb"]

for (var x=0; x<a.length; x++) {
    a[x] = a[x].replace(/Strange\s+/, "");
    console.log(a[x]);
}

Upvotes: 1

Related Questions