2

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!

3
  • what is your problem? find the array element in sourcecode or something else? Commented Jun 12, 2013 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. Commented Jun 12, 2013 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. Commented Jun 12, 2013 at 3:41

2 Answers 2

3

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

OK, I need to figure out what you are doing here exactly but I will try it out. Thank you!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.