JavaScript Strings
First must know what objects are in programming and the fundamental concepts of the object-oriented programming (OOP), becouse the string is recognized as an object in JavaScript.
JavaScript isn't a object-oriented (OO), such as C++ or Java, but is based on objects.
In the world around us the objects are, for example: a book, a car, a television ..., In JavaScript the object s are, for example: a form, a window, buttons, images, strings ...
JavaScript sees all elements of a page as objects.
An object is a collection of values called properties.
When a property is function, it’s referred to as a method.
1. String object
There is various ways to create a string: using the new keyword or with the literal form, surround characters with either single quotes (') or double quotes (").
var instance_name = new String("string value here"); // using the "new" keyword
// Literal form
var variable_name1 = "some text: coursesweb.net"; // with double quotes
// or
var variable_name1 = 'some text: coursesweb.net'; // with single quotes
- The most indicated way is the literal form (with quotes).But whichever quote you use (single or double), you can’t use it again in the middle of the string because that will end the string early.
However, you can escape any character with a backslash (\) to solve this or use single primes inside double primes (and vice versa).
<script type="text/javascript"><!-- // Incorrect var a_name = "CoursesWeb.net "JS lesson""; // SyntaxError: missing ; before statement // Correct var a_name = "CoursesWeb.net \"JS lesson\""; // or var a_name = 'CoursesWeb.net "JS lesson"'; // or var a_name = "CoursesWeb.net 'JS lesson'"; --></script>
Strings have one built-in property, length.
- length - returns the number of characters in a string
<script type="text/javascript"><!-- var a_name = 'CoursesWeb.net "JS tutorials"'; alert(a_name.length); // 27 --></script>
2. String Methods
The String object has a lot of methods, as shown:Methods That Add HTML Tags
- anchor(name) - used to create an HTML anchor. Returns the string embedded in the <a> tag (<a name="anchorname">string</a>)
<script type="text/javascript"><!-- var txt = 'String object'; txt.anchor('strings'); alert(txt.anchor("myanchor")); --></script> - big() - display a string in a big font. Returns the string embedded in the <big> tag (<big>string</big>)
<script type="text/javascript"><!-- var str = "coursesweb.net"; document.write(str.big()); --></script>
- blink() - display a blinking string. Returns the string embedded in the <blink> tag (<blink>string</blink>)
<script type="text/javascript"><!-- var str = 'JavaScript strings'; document.write(str.blink()); --></script>
- bold() - display a string in bold. Returns the string embedded in the <b> ta (<b>string</b>)
<script type="text/javascript"><!-- var str = 'JavaScript strings'; document.write(str.bold()); --></script>
- fixed() - display a string as teletype text. Returns the string embedded in the <tt> tag (<tt>string</tt>)
<script type="text/javascript"><!-- var str = 'String object'; document.write(str.fixed()); --></script>
- fontcolor(color) - display a string in a specified color. This method returns the string embedded in the <font> tag (<font color="color">string</font>)
<script type="text/javascript"><!-- var str = 'String object'; document.write(str.fontcolor('blue')); --></script> - fontsize(size) - show a string in a specified size (between 1 and 7); embedded in the <font> tag (<font size="size">string</font>)
<script type="text/javascript"><!-- var txt = "Have a good day"; document.write(txt.fontsize(5)); --></script>
- italics() - show a text in italic. Returns the text in the <i> tag (<i>text</i>)
<script type="text/javascript"><!-- var txt = "Have a good day"; document.write(txt.italics()); --></script>
- link(url) - makes a string as a hyperlink. This method returns the string in the <a> tag (<a href="url">string</a>)
<script type="text/javascript"><!-- var str = "Free Web Developments Tutorials"; document.write(str.link("http://coursesweb.net")); --></script> - small() - display a text in small font, return it in <small> (<small>text</small>)
<script type="text/javascript"><!-- var str = "Web programming"; document.write(str.small()); --></script>
- strike() - display a string that is struck out. Return it in the <strike> (<strike>string</strike>)
<script type="text/javascript"><!-- var str = "Web programming"; document.write(str.strike()); --></script>
- sub() - display a string as subscript text. Return it in the <sub> (<sub>text</sub>)
<script type="text/javascript"><!-- var str = "JS programming"; document.write(str.sub()); --></script>
- sup() - display a string as superscript text. Return it in the <sup> (<sup>text</sup>)
<script type="text/javascript"><!-- var str = "JS strings tutorial"; document.write(str.sup()); --></script>
Other string object Methods
- charAt(index) - Finds out which character is at a given position (index) in a string.
<script type="text/javascript"><!-- var str = "JS strings methods"; alert('First character: '+ str.charAt(0)); --></script> - charCodeAt(index) - Finds the Unicode of a character at a given position in a string
<script type="text/javascript"><!-- var str = 'Hy there'; alert("Unicode first character: "+ str.charCodeAt(0)); --></script> - concat(string2, string3, ..., stringX) - Adds two or more strings together and returns the new combined string value
<script type="text/javascript"><!-- var str1="JS "; var str2="course"; alert(str1.concat(str2)); --></script>
- fromCharCode(n1, n2, ..., nx) - converts Unicode values to characters. (It is a static method of the String object. The syntax is always String.fromCharCode() and not "string.fromCharCode()").
<script type="text/javascript"><!-- alert(String.fromCharCode(52,68,78,86,99)); // 4DNVc --></script>
- indexOf(searchstring) - searches for a character sent as a parameter in a string: if it’s found, the position of the first instance of the character is returned; otherwise, it returns –1
<script type="text/javascript"><!-- var txt = "String methods"; alert(txt.indexOf('me')); // 7 --></script> - lastIndexOf(searchstring) -returns the position of the last found character sent as a parameter in a string: if it’s found, the position of the last instance of the character is returned; otherwise, it returns –1
<script type="text/javascript"><!-- var txt = "String methods"; alert(txt.lastIndexOf('t')); // 9 --></script> - match(regexp) - Compares a regular expression and a string to see if they match. Rreturns the matches or null.
<script type="text/javascript"><!-- var str = "JS lessons"; var regx = /on/gi; alert(str.match(regx)); // on --></script>
- replace(regexp/substr, newstring) - searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with 'newstring'.
<script type="text/javascript"><!-- var str="Visit http://coursesweb.net"; document.write(str.replace("coursesweb", "marplo")); // Visit http://www.marplo.net --></script> - search(regexp) - Executes the search for a match between a regular expression and a specified string. Returns the position of the match, or -1 if no match is found.
<script type="text/javascript"><!-- var str="Tutorials"; alert(str.search("tutor")); // -1 --></script> - slice(start, end) - Pulls out a specified section of a string (between start index and the end index) and returns a new string, or -1.
<script type="text/javascript"><!-- var str ="Tutorials"; alert(str.slice(0, 4)); // Tutor --></script>
- split(separator, limit) - Separates a string into an array of strings based on a separator sent as a parameter to the method. Limit is optional (an integer that specifies the number of splits).
<script type="text/javascript"><!-- var str="How are you?"; var ar_str = str.split(" "); alert(ar_str[1]); // are --></script> - substr(start, length) - returns a portion of the string specified with a starting position and through the specified number of character (length)
<script type="text/javascript"><!-- var str = "JS Tutorials"; alert(str.substr(3, 5)); // Tutor --></script>
- substring(from, to) - extracts the characters from a string, between two specified indices (not including "to" itself), and returns the sub-string
<script type="text/javascript"><!-- var str="Hy everyone"; document.write(str.substring(3, 7)); // ever --></script>
- toLowerCase() - Converts a string to all lowercase letters and returns the result
<script type="text/javascript"><!-- var txt = 'I love God'; document.write(txt.toLowerCase()); --></script>
- toUpperCase() - Converts a string to all uppercase letters and returns the result
<script type="text/javascript"><!-- var txt = 'I love God'; document.write(txt.toUpperCase()); // I LOVE GOD --></script>
Global Functions
- escape(string) - converts most special characters to hexadecimal character codes. It leaves letters, digits, and the following characters alone: @ * _ + - . /
<script type="text/javascript"><!-- var txt = 'Be well @ 78 ?'; document.write(escape(txt)); // Be%20well%20@%2078%20%3F --></script>
- unescape(string) - performs the reverse operation of the escape() function.
<script type="text/javascript"><!-- var txt = 'Be%20well%20@%2078%20%3F'; document.write(unescape(txt)); // Be well @ 78 ? --></script>
- encodeURIComponent(string) - encodes characters that separate different components of a URL (except letters, digits, and the following characters: - _ . ! ~ * ` ( ) )
So you can safely encode a string for use as a single component. This is most commonly used for encoding a string for use as a query string value or parameter.<script type="text/javascript"><!-- var url = 'http://coursesweb.net/index.php?c=javascript'; document.write(encodeURIComponent(url)); // http%3A%2F%2Fcoursesweb.net%2Findex.php%3Fc%3Djavascript --></script>
- decodeURIComponent(string) - performs the reverse operation of the encodeURIComponent() function.
<script type="text/javascript"><!-- var url = 'http%3A%2F%2Fcoursesweb.net%2Findex.php%3Fc%3Djavascript'; document.write(decodeURIComponent(url)); // http://coursesweb.net/index.php?c=javascript --></script>
JavaScript didn’t include a method for trimming whitespace off the beginning and ending of a string until recently, so for most browsers you have to provide your own.
You can use the following function:
function stringTrim(s) {
return s.replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, "");
}