JavaScript strings are used for storing and manipulating text.
JavaScript Strings
A string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
Example
var carname = "Volvo XC60";
var carname = 'Volvo XC60';
var carname = 'Volvo XC60';
You can access each character in a string with its position (index):
Example
var character = carname[7];
String indexes are zero-based, which means the first character is [0], the second is [1], and so on.
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
Or you can put quotes inside a string by using the \ escape character:
String Length
The length of a string (a string object) is found in the built in property length:
Finding a String in a String
The indexOf() method returns the position (as a number) of the first found occurrence of a specified text inside a string:
Example
var str = "Hello world, welcome to the universe.";
var pos = str.indexOf("welcome");
var pos = str.indexOf("welcome");
Try it Yourself »
The method returns -1 if the specified text is not found.
The lastIndexOf() method starts searching at the end of the string instead of at the beginning.
Matching Content
The match() method can be used to search for a matching content in a string:
Example
var str = "Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));
Try it Yourself »
Replacing Content
The replace() method replaces a specified value with another value in a string:
Example
str = "Please visit Microsoft!"
var n = str.replace("Microsoft","W3Schools");
var n = str.replace("Microsoft","W3Schools");
Try it Yourself »
Convert to Upper Case
A string is converted to upper case with the method toUpperCase():
Example
var txt = "Hello World!"; // String
var txt1 = txt.toUpperCase(); // txt1 is txt converted to upper
var txt1 = txt.toUpperCase(); // txt1 is txt converted to upper
Try it Yourself »
Convert to Lower Case
A string is converted to lower case with the method toLowerCase():
Example
var txt = "Hello World!"; // String
var txt1 = txt.toLowerCase(); // txt1 is txt converted to lower
var txt1 = txt.toLowerCase(); // txt1 is txt converted to lower
Try it Yourself »
Convert a String to an Array
A string is converted to an array with the built in method string.split():
Example
var txt = "a,b,c,d,e" // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
Try it Yourself »
Special Characters
The backslash (\) can be used to insert apostrophes, new lines, quotes, and other special characters into a string.
Look at the following JavaScript code:
var txt = "We are the so-called "Vikings" from the north.";
document.write(txt);
document.write(txt);
In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called
To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:
var txt = "We are the so-called \"Vikings\" from the north.";
document.write(txt);
document.write(txt);
JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.
The table below lists other special characters that can be added to a text string with the backslash sign:
| Code | Outputs |
|---|---|
| \' | single quote |
| \" | double quote |
| \\ | backslash |
| \n | new line |
| \r | carriage return |
| \t | tab |
| \b | backspace |
| \f | form feed |
Strings Can be Strings or Objects
JavaScript strings can be primitive values created from literals, like var x = "John";
JavaScript strings can also be objects created with the new keyword, like var y = new String("John");
Example
var x = "John";
var y = new String("John");
typeof(x) // returns String
typeof(y) // returns Object
var y = new String("John");
typeof(x) // returns String
typeof(y) // returns Object
Try it yourself »
Normally, because of some nasty side effects, you will not define strings as objects.
Example
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
Try it yourself »
Note: Primitive values, like "John", cannot have properties or methods (because they are not objects).
With JavaScript, all methods and properties of the string object are also available to primitive values, because Javascript will temporarily transfer primitive values to objects before executing the methods or properties.
String Properties and Methods
Properties:
- length
- prototype
- constructor
Methods:
- charAt()
- charCodeAt()
- concat()
- fromCharCode()
- indexOf()
- lastIndexOf()
- localeCompare()
- match()
- replace()
- search()
- slice()
- split()
- substr()
- substring()
- toLowerCase()
- toUpperCase()
- toString()
- trim()
- valueOf()
Complete String Reference
For a complete reference, go to our Complete JavaScript String Reference.
The reference contains descriptions and examples of all String properties and methods.
No comments:
Post a Comment