本文介绍在JavaScript中从字符串右侧截取指定字符的三种常用方法。通过substring结合length属性、正则表达式match以及slice负数索引实现。其中slice(-n)因语法简洁被推荐,适用于获取末尾固定长度子串的场景。
JavaScript右侧截取字符串的方法
提取abcdefg右侧的fg子串
使用substring截取
第一种方案
<script> string="abcdefg" alert(string.substring(string.length-2,string.length)) </script>
使用正则表达式匹配
第二种方案
<script> alert("abcdefg".match(/.*(.{2})/)[1]) </script>
<script> alert("abcdefg".match(/.{2}$/)) </script>
使用slice截取(推荐)
第三种方案
<script> alert("abcdefg".slice(-2)) //推荐这个,比较简单,-2表示取右边两个字符 </script>