Jump to content

Please help - split string into array and do a RegExp search in the array


spaceman12

Recommended Posts

I have been trying to sort this out by myself but it seems like I just can't figure to work it out correctly.

 

Suppose, I have a string like this-

var string="Where are you and Iam so sorry I cannot sleep I cannot dream tonight";

 

Here, lets assume that the string that I want to search for it is Where

var search= new RegExp["^Where$"];

 

I'm sure the object split() has got to do something with string and then do a testing.

 

Like this

var array=new array();
array=string.split(" ");

if(search.test(array))
{
document.write('true');
}

Despite all my efforts to make it work, I just can't.

 

In php, we could have easily split the string into arrays using explode and call the function

if(in_array($search,$array))
{
echo "true";
}

 

Please help(I'm just not very familiar with javascript) .Thanks :)

you would need to loop through the array to test

 

e.g.

for (var i=0; i<array.length; i++){
if(search.test(array[i])){document.write('true');}
}

 

p.s. document.write will overwrite the entier page.

exit() stops the rest of the php script from being parsed.  There is no javascript equivalent of php's exit(). 

 

As nogray mentioned, javascript "return" is the same as php's "return".  It stops the rest of a function from running, returning what you specify. 

 

Usually it is the last thing you do in a function if the function is expected to return a value (as a "best practice" functions should always return a value):

function blah() {
  var foo = 'bar';
  return foo;
}
x = blah();
alert(x); // will alert 'bar'

 

but it will also stop the function from completing wherever you put it:

 

function blah() {
  var x = 0;
  for (var c = 0; x < 10; c++) {
    if (c == 5) return x;
    x = c;
  }
  return x;
}
n = blah();
alert(n); 

 

In this example, the 2nd return will never be executed, because once c equals 5, the current value of x is returned, which breaks out of not only the loop, but the function itself.  if you just want to break out of the loop and not the whole function, use "break".

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.