Accessing individual parts of a string
An individual element is identified by using an index :
In this example, we can see that the 4th character is accessed
let myString = "Juniper berries"
console.log(myString[3])
Here we may want to access certain constiguos elements of the string. For this we use the function
substr()
In this example, we want to get 5 characters starting from the 4th charcter. Notice that:
In this example, we can see that the 4th character is accessed and then 5 characters taken
let myString = "Juniper berries"
console.log(myString.substr(4, 5))
This would output "iper "
One of the most important operations on strings is to determine its length.
This is done in JavaScript using a method called length
which is a property of the
string object
This delivers a count of the number of characters in the string.
In this example, we can see that the length of the string should be 15
let myString = "Juniper berries"
console.log(myString.length)
Here we use a FOR loop.
This method has the instructions for the counter to change as part of the Loop code.
There is a TEST BEFORE every repetition - it is definite.
let myString = "Juniper berries"
//loop through string
for (var index = 0; index < myString.length; index ++){
console.log(myString[index])
}
Here we use a FOR loop.
This method just takes each character as an object as part of the Loop code.
let myString = "Juniper berries"
//loop through string
for (character of myString){
console.log(character)
}
modelling.js
code