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