1

I was having fun with string methods and approached an issue while using slice on a string in the loop:

var sentence = document.querySelector('.newClass').textContent.split(' '),
    blank = '_________________________';

for(var i = 0; i < sentence.length; i += 1) {
    console.log(sentence[i] + blank.substring(blank.length, sentence[i].length) + i); //works
    console.log(sentence[i] + blank.slice(blank.length, sentence[i].length) + i); //???
}

CODE: http://jsfiddle.net/cachaito/Jxzd5/

I was sure string.slice() works same as string.substring()

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
cachaito
  • 343
  • 1
  • 6
  • 19

1 Answers1

2

There are some subtle differences, most of which are described here. However, the behavior you're seeing is because blank.length is always greater than sentence[i].length, and substring swaps the arguments in this case. From MDN:

If indexA is larger than indexB, then the effect of substring is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).

But slice doesn't do this. If the first argument is larger than the second, the result will be an empty string (assuming both are positive).

Try this:

for(var i = 0; i < sentence.length; i += 1) {
    console.log(sentence[i] + blank.substring(blank.length, sentence[i].length) + i); //works
    console.log(sentence[i] + blank.slice(sentence[i].length, blank.length) + i); //works
}

Or even this:

for(var i = 0; i < sentence.length; i += 1) {
    console.log(sentence[i] + blank.substring(blank.length, sentence[i].length) + i);
    console.log(sentence[i] + blank.slice(0, -sentence[i].length) + i);
}
Community
  • 1
  • 1
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • That's a brilliant answer! Thank You for explanation and link for 'What is the difference between String.slice and String.substring in JavaScript?' article :-) – cachaito Mar 21 '14 at 23:06