user4555547
user4555547

Reputation:

JavaScript's equivalent of String.trim?

I'm in a C# coding bootcamp and we are doing one week of JavaScript. The question here is if a given string starts with or ends with an "x" you omit that x. Ex: "xHix" becomes "Hi", "xHixx" would be come "Hix". My code is this

function stripX(str){
    if (str.substr(0,1) === "x")
        return str.substr(1,str.length);
    if (str.substr(str.length-1,1) === "x")
        return str.substr(0,str.length-1);
    return str;
}

I tried it in C# and it works fine, why doesn't it work here?! Thanks

Upvotes: 1

Views: 403

Answers (3)

wnbates
wnbates

Reputation: 753

Your code is returning if it finds an x at the start of the line, so will not replace the x at the end of the line. Modify the string variable first by using str = str.substr(...

Another alternative: Regular expressions can be used to match to the start of the string (^) or end of string ($) allowing this to be done in a single line.

function stripX(str) {
  return str.replace(/^x/, "").replace(/x$/, "");
}

alert(stripX("xHixx"));

Upvotes: 0

Oriol
Oriol

Reputation: 288120

You can try

function stripX(str){
    return str.substring(
        str[0] == 'x',
        str.length - (str[str.length-1] == 'x')
    );
}

Upvotes: 1

Mark Cidade
Mark Cidade

Reputation: 99957

You need to modify the string for both cases before returning it:

function stripX(str){
    if (str.substr(0,1) === "x")
        str = str.substr(1,str.length);
    if (str.substr(str.length-1,1) === "x")
        str = str.substr(0,str.length-1);
    return str;
}

Upvotes: 2

Related Questions