tags:

views:

77

answers:

3

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

+1  A: 

See indexOf

David Dorward
+2  A: 
<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>
Brian Scott
+2  A: 

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.

paxdiablo
Eugh. Using a regular expression for a simple pattern match is inefficient … and despite the documentation saying you need to pass in a regex ( https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/search ) , you are passing in a string … and you've escaped the `\` so its going to be looking for `\|Viewed` instead of `|Viewed` (or are you using some implementation of search that `eval`s strings in to regular expressions in that context (which is also dirty and should be avoided).
David Dorward
I suggest you try it, David, it works just fine. You _don't_ have to pass in a regex, one will be created for you if necessary. In addition, I didn't want to parrot just what had already been said, rather to provide a more powerful approach when needed. indexOf is fine for fixed strings and I congratulate you on your answer but sometimes I need more power. The double backslash is required because it's in a string so that the double becomes a single, and the single followed by the vertical bar is so we treat the bar as a specific character rather than the "or" separator.
paxdiablo