-4

so i'm currently trying to figure out what the code below will output. I'm confused by the substr function so if you could explain that it would be amazing. Thanks

    function getAttackString() {
    var foo = "d32329b34";
    var bar = "x38h309hj";
    return "The code is: "+(foo.substr(3,foo.length-6))+(bar.substr(2));
    }
    
    console.log(getAttackString());
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71

2 Answers2

0

3298h309hj

foo.substr(3, foo.length - 6 )) => get the substring of foo that is 6 chars shorter than foo starting at char 3 = 329

bar.substr(2) => get the substring of bar that starts at char 2 and returns all of the chars = 8h309hj

function getAttackString() {
var foo = "d32329b34";
var bar = "x38h309hj";
return "The code is: "+(foo.substr(3,foo.length-6))+(bar.substr(2));
}

console.log( getAttackString() );
JasonB
  • 6,243
  • 2
  • 17
  • 27
0

The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

The syntax for this function is

str.substr(start[, length])

start: Location at which to begin extracting characters. If a negative number is given, it is treated as strLength + start where strLength is the length of the string. For example, str.substr(-3) is treated as str.substr(str.length - 3)

length: The number of characters to extract. If this argument is undefined, all the characters from start to the end of the string are extracted.

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)

So applying it to your code:

function getAttackString() {
  var foo = "d32329b34";
  var bar = "x38h309hj";
  return "The code is: " + foo.substr(3,foo.length-6) + bar.substr(2);
}
    
console.log(getAttackString());

The expression foo.substr(3,foo.length-6) is extracting foo.length-6 (9-6=3) characters starting from the 4th character , 3, resulting in 329.

The expression bar.substr(2) is extracting all of the characters (since the second parameter, length, is undefined) starting from the 3rd character, 8, resulting in 8h309hj.

Put them together with the final expression and you get: The code is: 3298h309hj

Steven Goodman
  • 576
  • 3
  • 15