最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Need Js code to check pipe "|" present in a string - Stack Overflow

programmeradmin0浏览0评论

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|Viewed".

can anyone help me out ? THx

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|Viewed".

can anyone help me out ? THx

Share Improve this question edited Jun 28, 2010 at 13:28 oezi 51.8k10 gold badges102 silver badges119 bronze badges asked Jun 28, 2010 at 13:24 user367134user367134 9428 gold badges19 silver badges32 bronze badges 3
  • Do you mean js, or javascript? – skaffman Commented Jun 28, 2010 at 13:27
  • 2 @skaffman — JS is a perfectly acceptable abbreviation of JavaScript and doesn't have another meanings (except perhaps JScript, which is close enough to JavaScript as makes no difference in most cases, and should be explicitly mentioned anyway in the cases where it does). – Quentin Commented Jun 28, 2010 at 13:36
  • There is a language called JS: stackoverflow./questions/1148979/… Where is your god now? – user216441 Commented Jun 28, 2010 at 14:10
Add a ment  | 

2 Answers 2

Reset to default 3

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 plex 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>
发布评论

评论列表(0)

  1. 暂无评论