Before we got much deeper I had best cover strings.
Any time you want to store characters/words it will be as a string, a string can be anything from a single character to a novel if you have enough memory to store it.
Strings are shown definitely to variable names by surrounding them in single or double quotes for example
var myString = 'abc' // sets the variable myString to the string abc var myString2 = abc // sets the variable myString2 to be the same as (undeclared) variable abc
If a string is to contain quotes there are two ways to achieve this either by preceding the quote with the escape character \ or by using the other type of quote:
var str1 = 'he said "hello" to them' var str2 = "he said \"hello\" to them" //str1 == str2 var str3 = "he said "hello" to them" // error
str3 would cause an error as JS would see it as str3 = ‘string’hello’string’ and throw a syntax error, as you can see the error as the whole string is not highlighted blue in the code block
Two or more strings can be added together using the concat() method (see below) or by using the + operator eg:
var string = 'hello'; var string2 = 'world'; var myString = string + string2 // myString == 'helloworld' with no whitespace as it is not added automatically var myString2 = string + ' ' + string2 // myString2 'hello world' as there is a whitespace added between string1 and string2
Properties
property | function | example |
.length | gives the length of a string including any whitespace or special characters |
myStr.length |
As with most things strings are indexed from 0 so the character at 0 would be the first character in the string, this is an important point to remember when using these methods:
Methods
method | function | example |
.concat() | joins a two strings together | var str = ‘hello ‘; var str2 = ‘world’; str.concat(str2) == ‘hello world’ |
.split() | splits an array into an array at whatever char is in the bracket | var str3 = ‘hello world’; var x = str3.split(‘ ‘); // x == [hello,world] |
.includes() | checks to see if a string includes a specific string | x = str3.includes(hello); // x == true |
.replace() | replaces part of a string with another string | x = str3.replace(‘hello’, ‘goodbye’); // x == ‘goodbye world’ |
These are just some of the basics and I’ll cover more in another post
different
Hi there I am so ԁelighted I found youг bⅼog, I really found you
by accident, wһile I was browsing on Googⅼe for sometһing else, Anyways I am here noᴡ and would just like to say
many thanks for a fantastic post and a all round exciting blog (I also loѵe the theme/design),
I don’t have time to read through it аll at the minute
but I have saved it and also added in уour RSS feeds, so when I have time I will
be back to read much more, Pⅼease do keep up the excellent work.