0

How can I check via JQuery, if a object contains a string? For example I got this as a object:

<p>Lorem ipsum</p>
<p>Needle: in haystack</p>
<p>Anything: more text</p>

So now I want to check if this object contains one or more of this elements at the begining:

  • "Needle:"
  • "Something:"
  • "Anything:"

In this case two elements are found in that object. Now I need the output in a variable of "Needle, Anything"

I tried to use :contains and filter() but I failed with that.

<script type="text/javascript">
$(function() {
    var foundin = $('*:contains("Needle:")');
    if (foundin) {
        // extract part
    }
});
</script>
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • 2
    show the code you tried – Cfreak Aug 07 '14 at 19:32
  • Try this `sentence.indexOf(word) !== -1`. Where sentence is the string you want to search into and word is the word you are searching for. – Athafoud Aug 07 '14 at 19:37
  • possible duplicate of [How to see if string contains substring](http://stackoverflow.com/questions/3480771/how-to-see-if-string-contains-substring) – Athafoud Aug 07 '14 at 19:42

2 Answers2

1

Something like:

var values = ["Needle:", "Something:", "Anything:"],
    found = [];

$("*", obj).each(function() {
    for (var i = 0; i < values.length; i++) {
        if ( $(this).text().indexOf(values[i]) == 0 ) {
            found.push(values[i]);
            break;
        }
    }
});

console.log(found);

This assumes obj is your object of parsed HTML and useable by jQuery.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

I'm not exactly sure what the end result you are trying to achieve is, but you could use something like:

if (str.indexOf("Needle:") >= 0)

where str is your object.

Rob W.
  • 270
  • 6
  • 14