1

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

1
  • 2
    The return statement exits the function immediately. If you find a leading "x", you'll immediately return the string with the leading "x" stripped away, but a trailing "x" may still be there.
    – Pointy
    Feb 24, 2015 at 18:12

3 Answers 3

2

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;
}
1

You can try

function stripX(str){
    return str.substring(
        str[0] == 'x',
        str.length - (str[str.length-1] == 'x')
    );
}
1
  • Clever use of type coercion, but have to stop myself from upvoting just because of obscurity. Nice simplification though.
    – MDEV
    Feb 24, 2015 at 18:20
0

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"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.