String examples
Sometimes we just need to find out if a key word exists in a string.
This can be done by using the indexOf() method of the String object.
var s = navigator.userAgent;
var isIE = false;
if( s.indexOf("MSIE") != -1) isIE = true;
if(isIE) alert("it's an IE browser");
|
If the string MSIE is not found, the indexOf() method will return -1.
<script language="javascript" type="text/javascript">
var lan = navigator.language;
var lanCode = lan.substr(0,2);
document.writeln("Language = "+lan+" <br> Short code = "+lanCode );
</script>
|
The use of substr() in the code above yields the following output:
This is useful because it is often convenient to deliver language specific
content that falls into one of several major language groups (en, es, fr, etc.).
<script language="javascript" type="text/javascript">
if(lanCode == "es") document.writeln("Bienvenido a mi lugar en la Red!");
else if(lanCode == "fr") document.writeln("Bienvenue a ma page sur le Web.");
else document.writeln("Welcome to my site.");
</script>
|
Finally, we use the split() method of the string class to divide the title into words
<script language="javascript" type="text/javascript">
var words = window.document.title.split(" ");
document.writeln("Word 1 of the title is:"+words[0]+"<br>");
document.writeln("Word 2 of the title is:"+words[1]);
</script>
|
|