var str = 'This is a string';
var str = 'Hello' + ' World'; // Hello World
str += '!'; // Hello World!
var day = 13;
str += ' Today is the ' + day + 'th';
// Hello World! Today is the 13th
Something to think about is that strings are immutable. That means that already existing ones can't be modified. Instead every time you want to change something in them a new string must always be created. So they can't be modified directly with the brackets notation, only concatenated and modified with methods that returns a new string.
'\0'; // The nul character
'\b'; // Backspace
'\t'; // Tab
'\n'; // New line
'\r'; // Carriage return
'\v'; // Vertical tab
'\f'; // Form feed
'\"'; // Double quote
'\''; // Single quote
'\\'; // Backslash
Most of these won't be visible if used on most websites though (except in the source code). This is because html has it's own way of structuring and displaying contents. Like in html <br> tags are used for new lines, not "\n". The escape sequences are mostly for normal text that can be found in for example text files and word documents.
var str = 'Hello World';
str.length; // 11
Prototype is a common object that all strings share and is where all their methods are stored. Like the methods toLowerCase, slice and charAt and so on are all stored there, and it's even possible to define own methods and put them there. That's called extension methods, but is a topic for another time.
Constructor is mostly just used to return a reference to their constructor function.
CharAt is a method that takes a number as parameter. It will then return the character in the string at that position. If the number is a negative value or greater than its length, an empty string will be returned.
var msg = 'Hello there';
msg.charAt(0); // H
msg.charAt(4); // o
msg.charAt(msg.length - 1); // e
CharCodeAt and fromCharCode
CharCodeAt works just like charAt, except that instead of returning the character at the position, it returns the character code of the character. These codes are from the ascii table.
FromCharCode is a static method that does the opposite from charCodeAt, meaning it returns the character from a character code. It can by the way accept multiple parameters at once.
var fruit = 'Banana';
fruit.charCodeAt(0); // 66
String.fromCharCode(66) // B
String.fromCharCode(66, 97, 110) // Ban
Concat does exactly what it sounds like. It concatenates strings in the same way that the addition operator (+) does. It's just another way of doing it.
var name = 'Bob';
name.concat(' Johnsson'); // Bob Johnsson
name + ' Andersson'; // Bob Andersson
IndexOf, lastIndexOf and search
IndexOf is used to find out what position a character or word has in a string. It returns the position for the first match it encounters. If no match is found -1 is returned.
var msg = 'An old house';
msg.indexOf('n'); // 1
msg.indexOf('old'); // 3
msg.lastIndexOf('o'); // 8
msg.search(/old/); // 3
LastIndexOf does the same thing as indexOf except it returns the position of the last match it encounters.
Search works in a similar way but instead takes a regular expression as argument.
LocaleCompare is a method to compare and sort a string against another (after what characters they start with in the alphabet. If the one compared against should be sorted before -1 is returned, 1 for after and 0 for equal.
'abc'.localCompare('def'); // -1
'def'.localCompare('abc'); // 1
'abc'.localCompare('abc'); // 0
Match is a method that takes a regular expression as parameter. It will then look for everything that is matched and return the results as an array. In the example below everything that matches the word "book" is searched for with both small and capital letters.
var str = 'Book in a bookstore';
str.match(/book/gi); // ['Book', 'book']
Replace searches a string after matches just like match does. But instead replaces the matches to what's given in the second parameter. It takes both a string and a regular expression as the first parameter. If given a string it will only replace the first encounter, to replace multiple it must be given a regular expression with the "g flag".
var str = 'Webbdude is a cool blog';
str = str.replace('dude', 'jocke'); // Webbjocke is a cool blog
str = str.replace(/o/g, '0'); // Webbj0cke is a c00l bl0g
Slice does what it sounds like. It slices a string either from the start, end or from a custom position. The first parameter is the start position and the second parameter is the end position, which is optional.
var fruit = 'Orange';
fruit.slice(1); // range
fruit.slice(2, 5); // ang
fruit.slice(0, -2); // Oran
Split takes a string and splits it up into a bunch of smaller ones, then returning them in an array. It does it from the argument given which is the delimiter, and can be any character.
var arr = 'Masterchef is on the TV'.split(' ');
// ['Masterchef', 'is', 'on', 'the', 'TV']
arr = '1:2:3:4'.split(':'); // [1, 2, 3, 4]
ToLowerCase och toUpperCase
ToLowerCase is a simple and useful method that just converts all capital letters in a string to small. ToUpperCase converts all small letters to capital letters.
var str = 'Hello Bob';
str.toLowerCase(str); // hello bob
str.toUpperCase(str); // HELLO BOB
There are also the methods toLocaleLowerCase and toLocaleUpperCase. These are set from which language is used, and is required for some specific charsets that the normal lower and uppercase doesn't support.
var num = 44;
var arr = [0, 1, 2];
num.toString(); // '44'
arr.toString(); // '0,1,2'
There's also a toLocaleString if the common method doesn't find some language specific characters.
Trim removes all starting and ending whitespaces from a string. It's a very useful and common method, especially when working with text coming from users.
var str = ' Hello there ';
str.trim(); // 'Hello there'
Try it yourself
- Create a couple strings, concatenate them together with for example some variables or numbers, and print out the results in the web browser.
- Try out the different methods and properties and understand how they work.