开发者

javascript string.lastIndexOf does not work with span innerHTML

look the below example.

<html>
<body>
<form>
<span id="spTest">Your curre开发者_如何学Gont operation: Modify &raquo; newone</span>
</form>
<script type="text/javascript">
var sp = document.getElementById("spTest");
var str = sp.innerHTML;
//var str = "Your current operation: Modify &raquo; newone";
alert(str)
var index = str.lastIndexOf("&raquo;");
alert(index);

</script>

</body>
</html>

the above example will popup the "index" value -1. If I uncomment the line ""Your current operation: Modify » newone";", the result will be 30.

So I think the reason is because I use the "innerHTML" to get the text. What else can i use the get text inside span and get the right index result?

Thanks


No, it has nothing to do with innerHTML. In the call to lastIndexOf, the &raquo; entity is not expanded as it is in the HTML code; instead it is considered as a raw string. Replace it with the actual character and it will work:

var index = str.lastIndexOf("»");


If you use innerHTML, you have to use "»" instead of "&raquo;".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜