look the below example.
<html>
<body>
<form>
<span id="spTest">Your curre开发者_如何学Gont operation: Modify » newone</span>
</form>
<script type="text/javascript">
var sp = document.getElementById("spTest");
var str = sp.innerHTML;
//var str = "Your current operation: Modify » newone";
alert(str)
var index = str.lastIndexOf("»");
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 »
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 "»"
.
精彩评论