Wednesday, December 25, 2013

String



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.

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.
HTML:
<p id="p1">Here is some paragraph</p>

Javascript:
var p=document.getElementById("p1").innerHTML;

document.getElementById("p1").innerHTML=p.fontcolor('red');

//OR

document.getElementById("p1").innerHTML=p.fontcolor('A71616');
fontsize(size)
Returns the string with the tag <FONT size="size"> surrounding it.
italics()
Returns the string with the tag <I> surrounding it.
var p=document.getElementById("p1").innerHTML;
document.getElementById("p1").innerHTML=p.italics();
link(url)
Returns the string with the tag <A href="url"> surrounding it.
var p=document.getElementById("p1").innerHTML;
document.getElementById("p1").innerHTML=p.link('http://www.google.com');
small()
Returns the string with the tag <SMALL> surrounding it.
strike()
Returns the string with the tag <STRIKE> surrounding it.
var p=document.getElementById("p1").innerHTML;
document.getElementById("p1").innerHTML=p.strike();
sub()
Returns the string with the tag <SUB> surrounding it.
var p=document.getElementById("p1").innerHTML;
document.getElementById("p1").innerHTML="This is what a sub script" + p.sub() + "looks like";
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.
var anyString = "Brave new world";

alert("The character at index 0   is '" + anyString.charAt(0)   + "'");

alert("The character at index 15 is '" + anyString.charAt(15) + "'");

//The character at index 0 is 'B'
//The character at index 15 is ''
charCodeAt(index)
Index:
An integer greater than or equal to 0 and less than the length of the string; if it is not a number, it defaults to 0.

charCodeAt returns NaN if the given index is not greater than 0 or is     greater than the length of the string.
Note that charCodeAt will always return a value that is less than 65,536.
The following example returns 65, the Unicode value for A.
 
"ABC".charCodeAt(0) // returns 65

Returns the Unicode value of the character at position "index" 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: 74-97-118-97-83-99-114-105-112-116-32-75-105-116-
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 final1=he.concat(" loves ", “Janet”); // "Bob loves Janet"
var final=he.concat(" loves ", she); // "Bob loves Jane”
fromCharCode(c1, c2,...)
The static String.fromCharCode() method returns a string created by using the specified sequence of Unicode values.
Method of String object, not String instance. For example: String.fromCharCode("a").

Syntax

String.fromCharCode(num1, ..., numN)

Examples

The following example returns the string "ABC".
String.fromCharCode(65,66,67)
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")
toLowerCase()
Returns the string with all of its characters converted to lowercase.
var str="Hello World!";
alert(str.toLowerCase());

Returns: hello world!

toUpperCase()


Returns the string with all of its characters converted to uppercase.
var str="Hello World!";
alert(str. toUpperCase());

Returns: HELLO WORLD!

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.
Examples:
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]);
}
//4 alerts: "Welcome", "to", "JavaScript", and "Kit"

var str = "How are you doing today?";
var res = str.split(" ");  // returns: How,are,you,doing,today?


var str = "How are you doing today?";
var res = str.split(" ").reverse().join(" ");  // returns: today? doing you are How


var str = "Liril";
var res = str.split("").reverse().join("");
// split using character as delimiter including space
// returns:  liriL


var str = "23/03/1987";
var res = str.split("/").reverse().join("/"); //returns: 1987/03/23
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"]
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
}

localeCompare()
 The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
alert('a'.localeCompare('c')); // -2, or -1, or some other negative value
alert('c'.localeCompare('a')); // 2, or 1, or some other positive value
alert('a'.localeCompare('a')); // 0
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 oldstring="Peter has 8 dollars and Jane has 15";
newstring=oldstring.match(/\d+/g); 
// returns the array ["8","15"]

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 re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
alert(newstr);// oranges are round, and oranges are juicy.

var str = "Apples are round, and apples are juicy.";
var newstr = str.replace("apples", "oranges", "gi");
alert(newstr);// oranges are round, and oranges are juicy.

var oldstring="(304)434-5454";
newstring=oldstring.replace(/[-()]/g, "");
alert(newstring);
//returns "3044345454" (removes "(", ")", and "-")
Inside the replacement text, the following characters carry special meaning:
  • $1, $2, $3, etc.: References the sub matched 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:
"Mary is our mother".replace(/(Mary)/g, "$1 Johnson");
//returns "Mary Johnson is our mother"

var x="John Doe".replace(/(John) (Doe)/, "$2 $1");
//Doe John
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(beginSlice[, endSlice])
beginSlice
The zero-based index at which to begin extraction. If negative, it is treated as (sourceLength-beginSlice) where sourceLength is the length of the string.

endSlice
The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string. If negative, it is treated as (sourceLength-endSlice) where sourceLength is the length of the string.

Description

slice extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.
slice extracts up to but not including endSlice. str.slice(1,4) extracts the second character through the fourth character (characters indexed 1, 2, and 3).
As an example, str.slice(2,-1) extracts the third character through the second to last character in the string.

Example:
var str1 = "The morning is upon us.";
var str2 = str1.slice(4, -2);
alert(str2); // OUTPUT: morning is upon u

Example: Using slice with negative indexes

ar str = "The morning is upon us.";
str.slice(-3);     // returns "us."
str.slice(-3, -1); // returns "us"
str.slice(0, -1);  // returns "The morning is upon us"

Example:
"Replaces Billy with Dylan".slice(2);
//returns "places Billy with Dylan"

"Jane lives with Matthew”. slice(0,-3);
 //returns "Jane lives with Matt"
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.
substr(start, [length])
Returns the characters in a string beginning at "start" and through the specified number of characters, "length".
"Length" is optional, and if omitted, up to the end of the string is assumed.
The parameters behave in the following manner:
If start is positive and is greater than or equal to the length of the string, substr returns an empty string.
var str = "abcdefghij";
alert("(10): "   + str.substr(10));

If start is negative, substr uses it as a character index from the end of the string.
var str = "abcdefghij";
alert("(-3): "   + str.substr(-3)); // returns: (-3): hij
alert("(-3,2): "   + str.substr(-3,2)); // returns: (-3,2): hi

If start is negative and abs(start) is larger than the length of the string, substr uses 0 as the start index. Note: the described handling of negative values of the start argument is not supported by Microsoft JScript .
var str = "abcdefghij";
alert("(-12): " + str.substr(-12)); // returns: (-12): abcdefghij
alert("(-20, 2): " + str.substr(-20,2)); //returns” (-20, 2): ab
If length is 0 or negative, substr returns an empty string.
var str = "abcdefghij";
alert("(1,0): "   + str.substr(1,0));
alert("(1,-1): "   + str.substr(1,-1));
If length is omitted, substr extracts characters to the end of the string.
print("(1): "      + str.substr(1)); // (1): bcdefghij
Also consider:
var str = "abcdefghij";
alert("(0,13): "   + str.substr(0,13)); //returns: (0,13): abcdefghij

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(indexA[, indexB])
substring extracts characters from indexA up to but not including indexB.
"To" is optional, and if omitted, up to the end of the string is assumed.

The parameters behave in the following manner:
  • If indexA equals indexB, substring returns an empty string.
  • If indexB is omitted, substring extracts characters to the end of the string.
  • If either argument is less than 0 or is NaN, it is treated as if it were 0.
  • If either argument is greater than stringName.length, it is treated as if it were stringName.length.
If indexA is larger than indexB, then the effect of substring is as if the two arguments were swapped;
For example: str.substring(1, 0) == str.substring(0, 1).

Example1:

// assumes a print function is defined
var anyString = "Mozilla";

// Displays "Moz"
print(anyString.substring(0,3));
print(anyString.substring(3,0));

// Displays "lla"
print(anyString.substring(4,7));
print(anyString.substring(7,4));

// Displays "Mozill"
print(anyString.substring(0,6));

// Displays "Mozilla"
print(anyString.substring(0,7));
print(anyString.substring(0,10));
  
Example2:
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"

No comments:

Post a Comment