hI I WANT a script TO CHECK atleast one occurrence of "|Viewed" word is present in js string. sample Js sting wolll be "22|Test|Viewed,22|Test|Un-Viewed,22|Test|V开发者_高级运维iewed".
can anyone help me out ? THx
Others have already mentioned indexOf where you can do:
<html><body><script type="text/javascript">
var str="22|Test|Viewed,22|Test|Un-Viewed,22|Test|Viewed";
document.write(str.indexOf("|Viewed"));
</script></body></html>
but I'd like to also mention a more powerful option (if needed) - you can use the regex string search method:
<html><body><script type="text/javascript">
var str="22|Test|Viewed,22|Test|Un-Viewed,22|Test|Viewed";
document.write(str.search("\\|Viewed"));
</script></body></html>
Typing either of these into a file (xx.html
) and loading it in your browser, you'll see the number 7 appear which is the first position of the string found. This value is zero-based (0 is the first position) and you'll get back -1 if it cannot be found.
The regex version will allow more complex search patterns, not necessary for this specific case, but you should keep it in mind for when a simple constant string may not suffice.
<html><body><script type="text/javascript">
var my_string = "22|Test|Viewed,22|Test|Un-Viewed,22|Test|Viewed";
var the_matchIndex = my_string.indexOf('|Viewed');
var blMatch = the_matchIndex > -1;
alert(blMatch ? "Found a match!" : "No match found");
</script></body></html>
精彩评论