Categories:

JavaScript Kit > JavaScript Reference > Here

String Object

Last updated: June 27th, 2011

The String object of JavaScript allows you to perform manipulations on a stored piece of text, such as extracting a substring, searching for the occurrence of a certain character within it etc. For example:

var sitename="JavaScript Kit" //example string
alert(sitename.length) //alerts 14, the total number of characters

Related Tutorials

Escape sequences

For a list of Escape Sequences in JavaScript, such as newline, see here.

Properties

Properties Description
length Returns the length of the string (# of characters).
prototype Use this property to attach additional properties and/or methods that get reflected in all instances of the String.

Methods

Note: "[]" surrounding a parameter below means the parameter is optional.

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.

var myname="Peter Don"
document.write(myname.fontcolor("blue")) //writes out "Peter Don" in blue

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.
charAt(x) Returns the character at the "x" position within the string, with 0 being the position of the first character within the string.
charCodeAt(x) Returns the Unicode value of the character at position "x" within the string. In IE, this is a method of a String instance only, while in Firefox, it is also an instance of the String object itself (ie: String.charCodeAt("a")). Example:

var sitename="JavaScript Kit"
for (var i=0; i<sitename.length; i++)
document.write(sitename.charCodeAt(i)+"-")

Demo:

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. Example:

var he="Bob"
var she="Jane"
var final=he.concat(" loves ", she) // "Bob loves Jane"

fromCharCode(c1, c2,...) Returns a string created by using the specified sequence of Unicode values (arguments c1, c2 etc). Method of String object, not String instance. For example: String.fromCharCode("a").
indexOf(substr, [start]) Searches and (if found) returns the index number of the 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. Example:

"abcdefg".indexOf("h") //returns -1, as "h" isn't in string

var myname="John Miller"
myname.indexOf("Miller") //returns 5, the starting index of "Miller"

lastIndexOf(substr, [start]) Searches and (if found) returns the index number of the 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. Example:

"javascript kit".lastIndexOf("t") //returns 13
"javascript kit".lastIndexOf("p") //returns 8
"javascript kit".lastIndexOf("p", 5) //returns -1 (searches starting from "r" until "j")

localeCompare()  
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. The following extracts all the numbers inside a string and returns them as an array of numbers:

var winners="The winning numbers are 4, 56, 21, and 89"
winners.match(/\d+/g) //returns ["4", "56", "21", "89"]

For more info on regular expressions and the match() method, see Regular Expressions.

replace( regexp, replacement) Replaces portions of a string based on the entered regexp object and replacement text, then returns the new string. The replacement parameter can either be a string or a callback function. Example:

var oldstring="(304)434-5454"
newstring=oldstring.replace(/[\(\)-]/g, "") //returns "3044345454" (removes "(", ")", and "-")

Inside the replacement text, the following characters carry special meaning:

  • $1,$2,$3, etc: References the submatched substrings inside parenthesized expressions within the regular expression. With it you can capture the result of a match and use it within the replacement text.
  • $&: References the entire substring that matched the regular expression
  • $`: References the text that proceeds the matched substring
  • $': References the text that follows the matched substring
  • $$: A literal dollar sign

Example:

//returns "Mary Johnson is our mother":
"Mary is our mother".replace(/(Mary)/g, "$1 Johnson")

For more info on regular expressions and the replace() method, see Regular Expressions.

search(regexp) Tests for a match in a string. It returns the index of the match, or -1 if not found. Example:

"Amy and George".search(/george/i)
//returns 8

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. Example:

"Replaces John with Mary".slice(2) //returns "places John with Mary"

The "end" index can be a negative number, in which case the end index is the very last character within the string offset to the left by the number entered. Example:

"Jane lives with Matthew".slice(0,-3) //returns "Jane lives with Matt"

split(delimiter, [limit]) Splits a string into many according to the specified 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. Example:

var sitename="Welcome to JavaScript Kit"
var words=sitename.split(" ") //split using blank space as delimiter
for (var i=0; i<words.length; i++)
alert(words[i]) //alerts "Welcome", "to", "JavaScript", and "Kit"

The delimiter can be a regular expression, for example:

"1,2, 3,  4,   5".split(/\s*,\s*/) //returns the array ["1","2","3","4","5"]

substr(start, [length]) Returns the characters in a string beginning at "start" and through the specified number of characters, "length". The parameters behave in the following manner:
  • 0 indicates the first character in the string.
  • If start >= length of string, substr() automatically returns empty string.
  • If start < 0, such as -2, substr() begins from the end of the string backwards abs(start) characters. So "12345".substr(-2) will begin at "4", or 2 characters from the end of the string.
  • If start < 0 and start > length of string, start is set to 0 instead.
  • "Length" is optional, and if omitted, up to the end of the string is assumed.

Examples:

var n="123456789"
n.substr(0,4) //returns "1234"
n.substr(1) //returns "23456789"
n.substr(-1) //returns "9"
n.substr(-5,4) //returns "5678"

substring(from, [to]) Returns the characters in a string between "from" and "to" indexes, NOT including "to" inself. "To" is optional, and if omitted, up to the end of the string is assumed. The parameters behave in the following manner:
  • If either "from" and "to" are less than 0, 0 is used instead.
  • If "to" is omited, end of the string is assumed.
  • If "from" is larger than "to", then substring() automatically swaps the two arguments before returning the result.

 Example:

var n="123456789"
n.substring(0,4) //returns "1234"
n.substring(1) //returns "23456789"
n.substring(-1) //returns "123456789"
n.substring(-5,4) //returns "1234"
n.substring(4,-5) //returns "1234"

toLowerCase() Returns the string with all of its characters converted to lowercase.
toUpperCase() Returns the string with all of its characters converted to uppercase.
trim()

IE9+, FF3.5+, WebKit

Trims a string on both sides for any spaces and returns the result. The original string is unmodified: Example:

var sitename=" JavaScript Kit   "
alert(sitename.trim()) //alerts "JavaScript Kit". Variable itself unchanged.

Since trim() is not yet supported in all browsers (most notably IE), it should be coupled with a fall back method for achieving the same result in those lesser browsers, such as via regular expressions. The following example uses trim() in capable browsers, and regular expressions instead in non capable to trim a string:

Cross Browser Example:

function trimstring(str){
 if (str.trim)
  return str.trim()
 else
  return str.replace(/(^\s*)|(\s*$)/g, "") //find and remove spaces from left and right hand side of string
}

trimstring(" JavaScript Kit   ")


Reference List

Right column

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info