Strings

·

2 min read

Strings are collections of characters. they are created to store and manipulate text. strings are stored inside of quotes. you can also store symbols and numbers inside strings. a string is a data type.

Example:

let jessePinkman= "yeah bitch!!" //double quotes
let walterWhite='You are god damn right!' //single quotes
//You can use quotes inside a string, as long as they don't match the quotes surrounding the string

let walterwhiteV2="I'm the Danger!!"

string.length is a property to find the length of strings/number of characters inside of a string. numbering (index value) starts from 0 and not 1. space between words is also calculated/ also have index value.

//here the string length should be 5 but actually it's 4
let country= "INDIA"
console.log(country.length)

string methods:

methods are set of instructions that perform a task. they are similar to functions. the only difference is, the method is associated with an object and the function is not.

methods are used to manipulate strings here are some of the javascript methods:

.toUpperCase() = converts the whole string to uppercase.

.toLowerCase()\=converts the whole string to lowercase.

.replace(parameter1, parameter2) = takes two parameters. one is an existing value with another value in a string. by default it replaces only the first match.

.replaceAll(parameter1, parameter2) = replaces all the existing values with another value in a string.

let quote = "the quick brown fox jumps over the lazy dog"

console.log(quote.toUpperCase()) 
console.log(quote.toLowerCase()) 
console.log(quote.replace("dog","elephant")) 
console.log(quote.replaceAll("o","a"))

.concat\= joins two or more strings. you can also use the addition sign (+) to concatenate.

.trim()\= removes whitespace from both sides of a string.

.charAt()\=returns the character at a specified index (position) in a string.

.split()\= converts a string to an array.

let variable1= "here is a example of"
let variable2="   two different strings"
let array1= variable1 + variable2
console.log(variable1.concat(variable2)) 
console.log(variable2.trim()) 
console.log(variable2.charAt(7)) 
console.log(array1.split(" ") )

.slice()\= extracts a part of a string and returns the extracted part in a new string. it takes 2 parameters(start position, end position), where end is not included.

you can give a negative index number to a string. negative string number starts from the last character in a string to the first character of a string.

let text = "Apple, Banana, Kiwi ";
let withPositive = text.slice(7, 13);
let withNegative = text.slice(-1,-5 )
console.log(withPositive)
console.log(withNegative)