Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I think my question is fairly straightforward but I'm not very experienced with Javascript. What I am trying to do is pull the source code of a page and stick it all into a variable:

var sourcecode = document.documentElement.innerHTML;

Then I have an array of terms that I want to search that variable for:

var array = ['Huskers','Redskins','Texans','Rockets'];

I would like to assign a 0 to any of the array elements that aren't found in the sourcecode variable and a 1 to any that are. So, when the search is complete each array element will be represented by a variable that will either equal 1 or 0. Can anyone please give me a hint as to how I should go about this?

Thanks!

share|improve this question
 
what is your problem? find the array element in sourcecode or something else? –  leonhart Jun 12 at 3:14
 
I know how to search through the sourcecode for individual strings: If (sourcecode.indexOf('Huskers')) != -1 {Huskers = 1} but I'm thinking that if I do each search separately it will have to scroll through the entire string each time. –  Jared Venema Jun 12 at 3:33
 
so this is the critical problem, you should add it to you post otherwise you only get answer about how to search them one by one. –  leonhart Jun 12 at 3:41

2 Answers

up vote 1 down vote accepted

A bit cryptic but does what you need:

var source = 'lorem hello foo bar world';
var words = ['hello','red','world','green'];

words = words.map(function(w){ return +!!~source.indexOf(w) });

console.log(words); //=> [1, 0, 1, 0]

+!!~ casts a number of the boolean representation of the value returned by indexOf, same as:

return source.indexOf(w) == -1 ? 0 : 1;

But a bit shorter.

Note that indexOf matches strings within strings as well, if you want to match whole words you can use regex with word boundaries \b:

words = words.map(function(w) {
  return +new RegExp('\\b'+ w +'\\b','gi').test(source);
});
share|improve this answer
 
OK, I need to figure out what you are doing here exactly but I will try it out. Thank you! –  Jared Venema Jun 12 at 3:34
 
See my edit, I clarified the operators. –  elclanrs Jun 12 at 3:35
 
Thanks!!!!!!!!!!! –  Jared Venema Jun 13 at 3:29

If you want to find element in array you can use jquery $.inArray()

http://jsfiddle.net/hgHy4/

$(document).ready(function() {

var array = ['Huskers','Redskins','Texans','Rockets'];

    alert($.inArray('Redskins', array));


});

This will returns index number of element inside an array if it is found. If the element is not found it will return -1

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.