0% found this document useful (0 votes)
44 views

Formatting Text With Javascript

This document discusses formatting and handling strings in JavaScript. It provides an overview of the string-related properties and methods available in JavaScript, including formatting methods like toUpperCase() and link(), as well as handling methods like charAt(), indexOf(), and split(). Examples are given to demonstrate how to use these methods to format and manipulate strings programmatically in JavaScript.

Uploaded by

Zi Xi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Formatting Text With Javascript

This document discusses formatting and handling strings in JavaScript. It provides an overview of the string-related properties and methods available in JavaScript, including formatting methods like toUpperCase() and link(), as well as handling methods like charAt(), indexOf(), and split(). Examples are given to demonstrate how to use these methods to format and manipulate strings programmatically in JavaScript.

Uploaded by

Zi Xi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Page 1 of 4

Formatting text using JavaScript


To help format text programmatically, JavaScript exposes several default
methods and a single property for which the String object commands, and
all of which any text-containing variable can directly access. The below
table lists them:
Formatting related properties & methods of the String object
Property Description
length Returns the total number of characters of a string.
Methods Description
anchor(name) Returns the string with the tag <A name="name">
surrounding it.
big() Returns the string with the tag <BIG> surrounding it.
blink() Returns the string with the tag <BLINK> surrounding it.
bold() Returns the string with the tag <B> surrounding it.
fixed() Returns the string with the tag <TT> surrounding it.
fontcolor(color) Returns the string with the tag <FONT color="color">
surrounding it. .
fontsize(size) Returns the string with the tag <FONT size="size">
surrounding it.
italics() Returns the string with the tag <I> surrounding it.
link(url) Returns the string with the tag <A href="url">
surrounding it.
small() Returns the string with the tag <SMALL> surrounding it.
strike() Returns the string with the tag <STRIKE> surrounding it.
sub() Returns the string with the tag <SUB> surrounding it.
sup() Returns the string with the tag <SUP> surrounding it.
toLowerCase() Returns the string with all of its characters converted to
lowercase.
toUpperCase() Returns the string with all of its characters converted to
uppercase.
Using the above with any string variable is simple enough- start with the
variable, then dot (.), then the property/method in question to call it. Let's
see this in action:
1
<script type="text/javascript">
2
var sitename="JavaScript Kit"
3
alert(sitename.length)
4
</script>
5
As soon as variable "sitename" contains text, it becomes more than just a
mere container, but an instance of the String object, with access to all of
it's goodies. And lots of goodies there are!
The syntax to using the object's methods is exactly the same. Take a look
at the following, which builds up a "normal" looking text into something
not, illustrating the use of these methods along the way:
1 var message="Welcome to our site!"
2 document.write(message)
Output:
Welcome to our site!
1 var message="Welcome to our site!"
2 document.write(message.toUpperCase())
Output:
WELCOME TO OUR SITE!
1 var message="Welcome to our site!"
2 document.write(message.toUpperCase().bold())
Output:
WELCOME TO OUR SITE!
1 var message="Welcome to our site!"
2 var format=message.toUpperCase()
3 var size=1
4 for (i=0;i<message.length;i++){
5 document.write(format.charAt(i).fontsize(size).bold())
6 if (size<7)
7 size++
8 else
9 size=1
10 }
Output:
WELCOME TO OUR SITE!
Starting to think a little differently about the usability of these String
methods, are we?
Two points worth mentioning in the above. First off, notice how it is legal
to append the calling of multiple methods into one line:
1 message.toUpperCase().bold()
Also, it's important to realize just what really goes on when we apply
String methods to a piece of text- the appropriate tags simply get
enclosed around it. For example, if we were to call String.bold() on
"Hello", the result would be "<b>Hello</b>"...there's nothing magical that
happens beyond that.With that in mind, take a look at the below, and see
if you can tell why the produced text looks dramatically different than the
above "ascending font size" example":
var message="Welcome to our site!"
var format=message.toUpperCase().bold()
var size=1
for (i=0;i<format.length;i++){
document.write(format.charAt(i).fontsize(size))
if (size<7)
size++
else
size=1
}
Output:
<b>WELCOME TO OUR SITE!</b>
Since String.bold() is applied to the message before any other, and the
result stored in variable "format", the manipulation that follows modifies
also the literal string "<b></b>", as seen in the output.
Ok, and with that we come to the end of this tutorial. As mentioned, the
methods just seen represent only a subset of all of that String supports. In
Part 2 of "Strings in JavaScript", I'll examine the ones dealing with the
dissecting/ searching, and manipulating of text.
Tutorial introduction
Formatting text using JavaScript
Page 2 of 4
In Part 1 of Strings in JavaScript, we looked at how to format text using
JavaScript, and along the way uncovered a hidden talent of the language.
In this follow-up/ concluding tutorial, things get a bit grittier as we
venture into the string itself, and learn how to slice and dice 'em . Let's
get the ball rolling..
String handling in JavaScript
String handling basically means the dissecting and manipulation of a
piece of string (not to be confused with string formatting). Some people
devote their entire careers to this task, though as JavaScripters, we aren't
known to exhibit such loyalty to the topic (or any other, for that matter!).
In this tutorial, we'll look at the methods of the String object that deal with
string handling, such as looking up a particular substring within a string,
splitting it into many, and more.
Tutorial introduction
String handling methods of the String object
String handling examples
String handling methods of the String object
Page 3 of 4
Here are the string handling related methods of the Stirng object, in full
force:
Methods Description
charAt(x) Returns the character at the "x" position within the
string.
charCodeAt(x) Returns the Unicode value of the character at position
"x" within the string.
concat(v1, v2,...) Combines one or more strings (arguments v1, v2 etc)
into the existing one and returns the combined string.
Original string is not modified.
fromCharCode(c1, Returns a string created by using the specified sequence
c2,...) of Unicode values (arguments c1, c2 etc). Method of
String object, not String instance. For example:
String.fromCharCode().
indexOf(substr, Searches and (if found) returns the index number of the
[start]) searched character or substring within the string. If not
found, -1 is returned. "Start" is an optional argument
specifying the position within string to begin the search.
Default is 0.
lastIndexOf(substr, Searches and (if found) returns the index number of the
[start]) searched character or substring within the string.
Searches the string from end to beginning. If not found,
-1 is returned. "Start" is an optional argument specifying
the position within string to begin the search. Default is
string.length-1.
match(regexp) Executes a search for a match within a string based on a
regular expression. It returns an array of information or
null if no match is found.
replace( regexp, Searches and replaces the regular expression portion
replacetext) (match) with the replaced text instead.
search(regexp) Tests for a match in a string. It returns the index of the
match, or -1 if not found.
slice(start, [end]) Returns a substring of the string based on the "start"
and "end" index arguments, NOT including the "end"
index itself. "End" is optional, and if none is specified,
the slice includes all characters from "start" to end of
string.
split(delimiter, Splits a string into many according to the specified
[limit]) delimiter, and returns an array containing each element.
The optional "limit" is an integer that lets you specify the
maximum number of elements to return.
substr(start, Returns the characters in a string beginning at "start"
[length]) and through the specified number of characters,
"length". "Length" is optional, and if omitted, up to the
end of the string is assumed.
substring(from, Returns the characters in a string between "from" and
[to]) "to" indexes, NOT including "to" inself. "To" is optional,
and if omitted, up to the end of the string is assumed.
toLowerCase() Returns the string with all of its characters converted to
lowercase.
toUpperCase() Returns the string with all of its characters converted to
uppercase.
At first glance, the above methods can appear a little intimidating to
some, so let's go over some of the more commonly used ones, method by
method:
-charAt(position)
charAt() simply returns the character at the specified position. For
example:
1
var message="internet"
2
alert(message.charAt(1))
3
-concat(v1, v2,..)
A "redundant" method, concat() combines the strings of its parameters
with the calling string. Here's an example:
1
var message="Bob"
2
var final=message.concat(" is a"," hopeless romantic.")
3
alert(final)
4
The reason for this method's redundancy is that it's often a lot simpler to
use the "+" operator instead to combine strings. The choice is yours, of
course.
-indexOf(char/substring)
An extremely useful string method, indexOf() allows you to search
whether a particular character or substring exists within a string, and if
so, where the first character of the character/substring is located. If no
match is found, "-1" is returned instead.
The below demonstrates using this method to determine whether the
word "George" exists in a sentence:
1 var sentence="Hi, my name is George!"
2 if (sentence.indexOf("George")!=-1)
3 alert("George is in there!")
Since it does, indexOf() will NOT return -1, but rather, the index number
of "G", and subsequently, the alert message will be executed.
If we were to tweak the sentence ever so slightly, so it reads:
1 var sentence="Hi, my name is Goerge!"
Running the same indexOf() code will return "-1" instead.
-slice(start, end)
As the name implies, slice() extracts out a substring from the string as
determined by the starting and ending points of it's parameters:
1 var text="excellent"
2 text.slice(0,4)
3 text.slice(2,4)
Simple enough, right?
-split(delimiter)
One of my personal favorite, split() cuts up a string into pieces, using
the delimiter as the point to cut off, and stores the results into an array.
"Say that again?", you say. Consider the following message:
1 var message="Welcome to JavaScript Kit"
Let's say I want to extract out the individual words ("Welcome", "to", etc)
from it. I would do the following:
Variable word instantly becomes an array that holds the individual words.
This is so because we used a space (" ") as the delimiter, which also is
what's separating each word.
To hammer down the point, here's the same message again, manipulated
by split() using a different delimiter this time:
1
var message="Welcome to JavaScript Kit"
2
var word=message.split("l")
3
The split() method is often used to parse values stored inside a cookie,
since they are by default separated by semicolons (;), a set delimiter.
-substring(from, to)
Last but not least, we arrive at substring(). This method simply returns
the substring beginning with the "from" parameter (included as part of
the substring), and ending with "to" (NOT included as part of substring).
It behaves just like the slice() method seen earlier. For example:
1 var text="excellent"
2 text.substring(0,4)
3 text.substring(2,4)
Exhale. We're at the end of the tunnel!
String handling methods of the String object
Page 4 of 4
Before we go our separate ways, wouldn't you like to see a couple of
examples on the utilization of these methods? Of course you would, and
here they are!
-Loose Email Check Example
Let's start with a classic. This first example loosely checks the content of
a form field to ensure it's a valid email address, by using indexOf() to
check for the presence of the "@" and "." character:
Source Code:
<form name="test"
1 onSubmit="checkemail(this.test2.value);return false">
2 <input type="text" size=20 name="test2"> <input
type="submit" value="Submit">
3
</form>
4
<script type="text/javascript">
5
function checkemail(which){
6
if (which.indexOf("@")!=-1 && which.indexOf(".")!=-1)
7
8 alert("Good!")
9 else
10 alert("Quit fooling around and enter a valid
email address!")
11
}
12
</script>
Note that I said "loose." "Simple" also is the script. All that's involved is
indexOf() and the number "-1" (which indicates the searched characters
are not present inside the form field).
-Word Count Example
Counting the number of words in any given text can be tedious a
task...without the help of the split() method, that is. Here's an example
using it (note the simplicity):
Source Code:
<form name="wordcount">
<textarea rows="12" name="wordcount2" cols="38" wrap="virtual">
</textarea><br>
<input type="button" value="Calculate Words" onClick="countit()">
<input type="text" name="wordcount3" size="20">
</form>
<script type="text/javascript">
function countit(){
var formcontent=document.wordcount.wordcount2.value
formcontent=formcontent.split(" ")
document.wordcount.wordcount3.value=formcontent.length
}
</script>
Gotta love split() (and this tutorial!).
String handling methods of the String object
String handling examples

You might also like