本文介绍了javascript子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最让人心寒的事!以下代码打印出'llo'而不是预期的'wo'。我得到了一些其他数字令人惊讶的结果。我在这里缺少什么?

  alert('helloworld'.substring(5,2)); 


解决方案

你很困惑和 : substring()期望两个索引而不是偏移量和长度。在您的情况下,索引是5和2,即将返回字符2..4,因为排除了较高的索引。


the most darndest thing! the following code prints out 'llo' instead of the expected 'wo'. i get such surprising results for a few other numbers. what am i missing here?

alert('helloworld'.substring(5, 2));
解决方案

You're confusing substring() and substr(): substring() expects two indices and not offset and length. In your case, the indices are 5 and 2, ie characters 2..4 will be returned as the higher index is excluded.

这篇关于javascript子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:29