String Methods By Chloe
'I am a string'2. With double quotations i.e
"I am also a string"3. Using template literals or backticks i.e
`You guessed it, I am a string too!`
String Concatenation:
This is the joining of two or more strings using the + symbol.var book = "Harry Potter" var author = "J K Rowling" var FaveBook = "My favourite book is " + book + " by" + author. console.log(FaveBook); My favourite book is Harry Potter by J K Rowling.
Template literals:
Template literals are a relatively new concept to JavaScript. It is simply constructing a string with backticks ``, instead of quotations.var TemplateString = `This string will print out on multiple lines because we used a template literal`Another benefit of template literal is string interpolation. This is a way of joining strings together usng ${}. This is quicker, easier and looks cleaner than string concatenation. e.g.
var book = "Harry Potter" var author = "J K Rowling" var FaveBook = `My favourite book is ${book} by ${author}` console.log(FaveBook); My favourite book is Harry Potter by J K Rowling.We have used the same example as above and as you can see it is a lot easier to read.
Methods
Different methods can be used to find information out about a string or manipulate a string in a particular way.METHOD | WHAT IT DOES | EXAMPLE |
---|---|---|
.toLowerCase | Converts all the characters in a string to lower case | var example = "I AM A UPPER CASE STRING" var example1 = example.toLowerCase(); -> "i am a upper case string |
.toUpperCase | Converts all the characters in a string to upper case | var text = "hello world" var text1 = text.toUpperCase -> "HELLO WORLD" |
.trim | Removes white space from either side. | var whiteS = " so much room "; var noWhiteS = whiteS.trim(); -> "so much room" |
.indexOf() | Finds the index of the first occurence of the string in brackets | var find = "Please locate the first locate word" var pos = find.indexOf("locate"); -> 7. |
.slice(start, end); | slices out the start number to end number [end] not included. | var fruit = "banana apple pear" var sliceFruit = fruit.slice(0, 6); -> "banana" |
.substr(start, [length]) | Prints out from start number for the length that it stated. | var hello = "hello world" var helloEx = hello.substr(2, 3); -> llo |
.repeat(x); | Repeats the string for by the number of times stated in brackets. | var hello = "hello world" var helloEx = hello.repeat(3); -> "hello world hello world hello world" |
.length | Returns the length of the string. | var hello = "hello" var helloEx = hello.length(); -> 5 |