Category: JavaScript Strings

Pad A String In JavaScript

24 September, 2008 | JavaScript Strings | No comments

Use the following function to pad a string with to a set length with a given string. The function takes three parameters. The string to be padded, the total number of characters that the string must be, and the string to be added. If the third parameter is not given then 0 is used as a default.

function pad(padMe, totalChars, padWith) {   padMe = padMe + ""; // force num to be string  padWith = (padWith) ? padWith :"0"; // set default pad  if ( padMe.length < totalChars ) {   while ( padMe.length < totalChars ) {     padMe = padWith + padMe;   }  }  return padMe; }

Here are some examples of the function in action. If the string given is longer than the required pad length then the string is returned unchanged.

alert(pad("1", 4, "0")); // 0001 alert(pad("9", 4, "7")); // 7779 alert(pad("0002", 7, "this is a string")); // this is a string 0002 alert(pad("12345", 4, "0")); // 12345

Written by Philip Norton.

JavaScript Word Counter

23 September, 2008 | JavaScript Strings | No comments

Counting the number of words in a block of text can be tricky. Users tend to create sections of white space that can throw out most scripts that don't take this into consideration.

I have created a tool for #! code that looks at a textarea of a form, and prints the number of words into an input box in the same form. The textarea calls a function called textCounter() every time a key is pressed. Here is the HTML of the form.

<form onsubmit="return false;" action="" id="wordCountCalc"> <textarea name="message1" rows="10" cols="68" onkeydown="textCounter()" onkeyup="textCounter()"></textarea> <input readonly="readonly" size="15" type="text" name="len" maxlength="10" value="0" /> </form>

The function works by removing any white space from the start of the text. It then removes any tab characters from the text before splitting the text by one or more white space characters.

The first step is to detect what browser the user is viewing the site in due to a discrepancy between how different browsers split a string apart by white space. The following snippet is used to detect browsers.

var sUserAgent = navigator.userAgent; var isOpera = sUserAgent.indexOf("Opera")>-1; var isIE = sUserAgent.indexOf("compatible")>1 && sUserAgent.indexOf("MSIE")>1 && !isOpera;

Here is the function that counts the number of characters in the textarea element.

function textCounter(){  var area = document.getElementById('wordCountCalc');  var formcontent;  if(area.message1.value.length != 0){   var reg;   reg = /^\s/gi;   formcontent = area.message1.value.replace(reg,''); // remove white space at start or string   reg = /\t+/g;   formcontent = formcontent.replace(reg,' '); // remove any tab characters   reg = /\s+/g;   formcontent = formcontent.split(reg); // split string by spaces   if ( isIE ) {    area.len.value = formcontent.length;   } else {    if ( area.message1.value.charAt(area.message1.value.length-1)==' ' ||     area.message1.value.charAt(area.message1.value.length-1)=='\n' ) {     area.len.value = formcontent.length-1;    } else {     area.len.value = formcontent.length;    };   };  }else{   area.len.value = 0;  }; };

Try it out for yourself on the number of words tool page. It has been tested quite extensively but if you find any issues or bugs then please post a comment.

Written by Philip Norton.

Using JavaScript To Select Textarea Text

1 July, 2008 | JavaScript Strings | No comments

This is a simple trick that will allow users to select the contents of a text area. First we need a text area.

<form><textarea name="textarea1" id="textarea1" rows="5" cols="40" wrap="off">This is some long content. This is some long content. This is some long content. This is some long content. </textarea> <br /> <input type="button" value="Select text" onclick="selectText('textarea1')"> </form>

This form also includes a button with an on click event that runs a function. This function takes a single parameter as the name of the element. It then sets the focus to this element and then selects all of the text therein.

function selectText(id){  var id = document.getElementById(id);  id.focus();  id.select(); }

Why is this useful? Well lets say you had a form or a quiz that produced and answer, and you wanted people to post their answer on their blogs, which then linked back to your quiz. This would allow users to select the contents of a text area without having to select it themselves.

Written by Philip Norton.

Flashing JavaScript Text

27 January, 2008 | JavaScript Strings | No comments

Here is a simple function that makes text in a tag fade into one colour slowly before quickly fading back into the original colour. If the background is the same colour as the text then the text will appear to fade in and out.

var color = 0; var dir = 1; function fade(){   var quick = 50;   var slow = 100;   var el = document.getElementById('fadeInOut');   if(!el){     return;   }     if(dir){     if (color < 255) {       setTimeout(fade,slow);       color += 10;     }else{       setTimeout(fade,quick);       color = 255;       dir = 0;     }   }else{     if(color > 0){       setTimeout(fade,quick);       color -= 10;     }else{       setTimeout(fade,slow);       color = 0;       dir = 1;     }   }   el.style.color = "rgb("+color+","+color+","+color+")"; }

This code works by using a group of setTimeout function calls to call the function in a loop. Each time the function is run some variables are set, the colour is changed and then the function is called again. Use it in the following way.

<body onload="fade();">   <div id="fadeInOut" style="font-size:100px;">Fading Text</div> </body>

So what would you use this for? Well if you where doing something intensive on a site you could use this trick to allow the user to see that things are going on before displaying the content that they requested.

Written by Philip Norton.

JavaScript Working Text

18 January, 2008 | JavaScript Strings | No comments

Letting the user now that something in the background is working is an essential part of website usability. If nothing at all happens then the user will more than likely either try again or go elsewhere. A good way of doing this is to have a little bit of text that says "Working" and animate dots behind it. Here is a function that will do this.

var strDots = ''; var dotLength = 10; var timeout = 500; function dots()   {   strDots += '.';   if ( strDots.length == dotLength ) {     strDots = '.';   }   document.getElementById('working').innerHTML = "<b>Working"+strDots+"</b>";   dotTimer = setTimeout('dots()', timeout); }

You then need to add the following bit of HTML to your page to start the dots off. The first one will print off:

Working

Followed by:

Working.

And so on. To get the code working on your page create a HTML element with an ID of working and include the following below that element.

<p id="working"></p> <script type="text/javascript" language="javascript">dots();</script>

To stop this you need to then call a second function.

function stopDots()   {   // stop the dots   if ( typeof(dotTimer) != 'undefined' ) {     clearTimeout(dotTimer);   }   document.getElementById('working').innerHTML = "<b>Done!</b>"; }

When you call this function the "Working" will be replaced by the text "Done!". If you are loading content in AJAX you can start the animation when the AJAX starts and then stop it when you get the data back from the server.

Another way of using this script is if you are flushing content to the browser with PHP you can start off the page by printing off the working function and then end the page with the stopDots() function. The browser will run the JavaScript as it comes through so you can create a nice little working notice on your pages that take a long time to load. This is a weird way of using JavaScript, but it does work on slow loading pages.

Written by Philip Norton.