JavaScript: How to Use the Search String
MatthewHSE
Status: Contributor
Joined: 20 Jul 2004
Posts: 122
Location: Central Illinois, typically glued to a computer screen
Reply Quote
I'm trying to learn JavaScript, and to match my learning style, I thought the best way to go at it was to just get started writing some little scripts.

The one I'm working on right now is to look at the URL in the location bar of the browser, see if it contains a certain string of characters, and if so, store a variable that I can use later in the <body> of the page. Here's what I have so far:

:: Code ::
<script type="text/javascript">
var url = window.top.location
var url_check = str.search("Matthew")
if (url_check != -1) {
   var result = "Matthew"
}
</script>


The idea would be to be able to use the following to print "Matthew" on the page:

:: Code ::
<script type="text/javascript">document.write(result)</script>


If you try that script, you'll find it doesn't work. The error is that "str.search is not a function." But I checked at w3schools.com, and that certainly looks like the proper syntax.

What am I missing here? Eventually this will be a very useful script to me, but only if I can get it to work! ;)

Thanks,

Matthew
Back to top
javascript search() object, window.top.location as object
erikZ
Status: Contributor
Joined: 30 May 2004
Posts: 148
Reply Quote
Hi Matthew, welcome to the wonderful world of Javascript.

There were many things wrong with your method, javascript is very difficult to learn in my opinion, and W3C schools is one of the worst places to learn it, as are most online resources. I strongly recommend getting a real programming reference book if you plan on pursuing javascript, or any programming language.

I use Dynamic HTML, the definitive reference Second Edition by the fairly great javascript guru Danny Goodman, that's on O'Reilly press, which puts out the best programming reference books in the world, I've never bought an O'Reilly book and regretted it. I also have Javascript, the definitive guide by David Flannigan, though I don't use that one as much, it's hardcore though. I like Dynamic HTML because it has a full DOM, CSS, and HTML reference, which is great, it's a massive reference book, 1400 or so pages.

Follow rigid, strict programming standards
Javascript is both extremely picky and extremely loose and sloppy, make sure you always follow extremely rigid programming discipline when you create your javascript programs to make sure its pickiness doesn't catch you up.

Debugging javascripts can be a massive pain, I have literally been unable to find bugs in a script, then cut and paste in a known working version, from another page, that appears exactly identical, then have it work fine.

This means:

  1. Always end every statement with a semicolon ;
  2. Never allow a string to have a line break in it without properly concatenating the string, like this:
    var test = 'of the world, we say hello' +
    'but do not care';

  3. Avoid using hardcoded constants in the functions, declare those values on top of the script, that makes debugging and maintaince a lot easier. (an exception would be in for example a switch test, where you are testing one variable for multiple possible string values). Anytime you are going to reuse a string make it a constant variable.

    Thus

    var condition1 = 'matthew';

    if ( condition1 )
    {
    statement;
    }


    is much easier to maintain long term than this, especially once your scripts start getting beyond 10 lines of code:

    if ( 'matthew' )
    {
    statement;
    }

  4. Always explicitly declare every single variable you are going to use first thing in the function or script, do not ever have an undeclared variable being used anywhere, for example, if result is going to be packed, declare it. You can either fill the variable with a value, or leave it unfilled, an unfilled variable always has the value of false, it becomes a boolean until you put something in it, then it becomes boolean value true, and has the value you put in it.

    You can use this syntax for declaring a group of variables:
    var result, str = document.URL, other_variable, another,
    yet_another = 'hello world';

    and so on.
  5. Leave whitespace for readability while developing, for example:
    function ( parameter )
    {
    value1 = parameter;
    return value1;
    }


    is much easier to read and debug than this:

    function(parameter){value1=parameter;return value1;}
  6. When developing any script, use
    document.write( str );
    at every step to see what values you are actually getting, or
    alert( str );
    , either works fine, although
    alert( str );
    is preferred since the script execution stops at the alert until you click 'ok'.
    [ str is in this case the variable you are testing. ]
  7. Unlike PHP, where ' and " have extremely different functions, I believe that in javascript they are more or less the same, not positive on that one. However, if I remember right, javascript doesn't let you put variables into strings like you can with PHP, since there is not actual variable delimiter ($) to tell js it is dealing with a variable and not a string.
  8. Never use implied structures, like
    if(condition)statement;
    Javascript is very loose, and let's you do this, but don't do it, it's a bad habit and makes debugging code very difficult.

    The correct syntax would be this:
    if ( condition )
    {
    statement;
    }


    The one exception to this, but even this one can bite you, is the if then else structure, same as in PHP.

    test_result = ( condition ) ? statement1 : statement2;

    I like this one when you have an if/else if clause and you are certain you won't need to add either extra statements or extra conditions.


Using typeof operator to determine what you actually have to work on
If you are in doubt, you can use the typeof operator to test the thing you are trying to get values out of like this:

alert( typeof window.top.location );

When you run this you will get an alert telling you it's an object. Javascript is confusing because there is no real way to tell objects, variables, or methods apart, that's why having a real reference book is critical.

What you want in this case is the standard string search method of indexOf( str ); and str = document.URL;, document.URL is a string, but it may not do exactly what you need it to do, we'll see.

With that in hand, here's what I found ( my test page is called search-test.htm, so the search string is 'search' ):

:: Code ::
<script type="text/javascript">
var result, search_term = 'search';
var str = document.URL;
alert( str );
var url_check = str.indexOf( search_term );
if ( url_check != -1 ) {
   var result = search_term;
}
</script>
<script type="text/javascript">document.write(result);</script>


or condensed:

:: Code ::
<script type="text/javascript">
var result, search_term = 'search', failure = 'test failure', str = document.URL;

result = ( str.indexOf( search_term ) != -1 ) ?  search_term : failure ;
document.write( result );
</script>


Condensed code is unreadable code but can be fun with Javascript
Javascript lets you use incredibly terse syntax, which can help drop file loading times, but makes it a lot less readable, opt for the expanded structures when you begin or you'll have a hard time deciphering your code later.

Here's a totally condensed version:

:: Code ::
<script type="text/javascript">
var d = document, r, st = 'search', f = 'test failure';
d.write( ( d.URL.indexOf( st ) != -1 ) ?  st : f );
</script>


The main script problems
There were several problems. First, window.top.location is not a string, it's an object. I tried using str = toString(window.top.location); but of course you can't turn an object into a string, it's an object. You learn something new every day.

Second, search() requires a regular expression to be fed into it, which means that search_term = 'search'; must become a regular expression pattern, which is far too complex for what you needed, regular expressions are very hard to grasp, and should only be used when they are necessary, which they aren't in this case. The stuff I've read says always use a standard string search function if there is one available because they are much more efficient, and also of course a lot easier.

A javascript regular expression would look like this:

str = /search/;

but it's not necessary, keep the learning curve low, don't try for regular expressions until you need to learn them. Also, once you create this regular expression pattern, if you print it out, you'll get this: /search/, not 'search', which isn't what you want.

So the correct function is this: indexOf(str);

Be very careful, by the way, of using advanced methods, they will fail cross browser, for example replace() was just supported in Opera as of version 7.5, search is probably similar, that's Ecmascript 3.0, no idea if Safari, Konqueror, or Opera support that anyway.

This is another reason that a real reference book is critical, with browser support charts for methods, objects, operators etc. I never use advanced methods because running multiple tests for browser support is a royal pain in the butt, and you literally never know when your script will break at some new browser bug, it makes CSS look absolutely simple in comparison.

Browser Support
The offbrand browsers, Opera, Safari, Konqueror, IE Mac is especially horrible in its javascript support, but none can ever be counted on to execute any script at all, since it all comes down to correct DOM/Ecmascript implementation. On the bright side, DOM is now well supported, so there is not need to use that horrible dual script support we needed to do in NS 4 days.

I'm not clear on why you are using window.top.location, is this in a frame? If so you might have problems, hard to say without knowing exactly it is you are trying to accomplish.
Back to top
Javascript query string parsing
bradster
Status: New User - Welcome
Joined: 20 Mar 2004
Posts: 4
Reply Quote
I found this script on [new user link]

:: Code ::
<HTML>
<HEAD>
<TITLE>Query String Parse Test</TITLE>

<SCRIPT language="Javascript">
function QueryString(key)
{
     var value = null;
     for (var i=0;i<QueryString.keys.length;i++)
     {
          if (QueryString.keys[i]==key)
          {
               value = QueryString.values[i];
               break;
          }
     }
     return value;
}
QueryString.keys = new Array();
QueryString.values = new Array();

function QueryString_Parse()
{
     var query = window.parent.location.search.substring(1)
     var pairs = query.split("&");
     
     for (var i=0;i<pairs.length;i++)
     {
          var pos = pairs[i].indexOf('=');
          if (pos >= 0)
          {
               var argname = pairs[i].substring(0,pos);
               var value = pairs[i].substring(pos+1);
               QueryString.keys[QueryString.keys.length] = argname               QueryString.values[QueryString.values.length] = value          }
     }

}
QueryString_Parse();

/
}
</SCRIPT>


Sadly, parsing query strings in Javascript is a lot harder than it should be, in PHP all you have to do is $_GET['parameter'']; and you're set.
Back to top
MatthewHSE
Status: Contributor
Joined: 20 Jul 2004
Posts: 122
Location: Central Illinois, typically glued to a computer screen
Reply Quote
Wow, lots to digest there. JavaScript was starting to seem kind of simple but you've managed to complicate things again beautifully! <grin>

I'll look over what you've posted in more detail to try to get my mind around it. Actually I'm in the process of learning PHP as well, and I had heard that PHP and JavaScript are similar enough that I decided to try to pick them both up at the same time. Maybe I should just stick with PHP until I have it down better.

Thanks for the loads of advice; I'll certainly heed your "good coding practices" in the future. I pride myself on writing clean HTML and CSS; didn't know enough about scripting to write clean JS but I think your tips will help me a long way on that road.

Thanks again!

Matthew
Back to top
bradster
Status: New User - Welcome
Joined: 20 Mar 2004
Posts: 4
Reply Quote
Javascript is pretty simple if you only use very simple methods, the basic operators are simple, <, >, <=, >=, ==, =, +, -, *, /, &&, ||, etc, but once you get into the objects, it's a big pain, I don't do much javascript stuff anymore because I'm sick of every new browser coming out failing to process the scrips I have up correctly, it's boring to fix, and not rewarding at all. I use some basic, stable scripts on most of my sites, and once in a while will do a real custom type programming thing, but it takes huge amounts of time to do anything real and have it actually work cross browser.

Since javascript's runtime environment is the actual program that uses it, like a browser, you are always depending on how good the browser programmers are, in the case of smaller browser, as mentioned, that support can be terrible, non-existent, or, most annoyingly, they will claim to support methods that they don't, Opera is especially bad about that, they pretend to support. document.all but they don't really, so if you test for if document.all sometimes opera will report true, very annoying.

Here's an old script I wrote, cut the url into IE or Opera > 7 to run it
techpatterns.com/downloads/scripts/christmascard.htm
I did it for a class and never rewrote it for document.getElementById(), which I wish I had of course.

That's the kind of stuff javascript is fun for, but it's pretty pointless. The main site uses a bunch of dynamic html too, all very complex, took weeks of work to get running right, not worth it every commercially except to learn. Nobody will pay for that stuff.

I just updated this one, you might get an error message or two before it starts on IE, and it almost crashes Mozilla, but runs perfect on Opera, go figure.

techpatterns.com/downloads/scripts/thanksgiving1.html

PHP, on the other hand, is another story, it has the same C based syntax as Javascript, so once you learn one version of a C derived language it's not that hard to learn more, but PHP pays.
Back to top
Display posts from previous:   

All times are GMT - 8 Hours