Strings

 What is Strings?

  • A Javascript string is a sequence of characters. It can be used to represent text, numbers, and other information. Examples are "Hello World", "1234", "true", "null", etc.
  • Strings can be declared in single, double, and back-tick quotes. 
  • To declare a string, we need a variable name, an assignment operator, a value under a single quote, double quote, or back

Creating a string
  • A string can be created by using string literals or by using a String() constructor.
String literal
  • It is the simplest way to create a string. Enclose the text content in single quotes ('), double quotes ("), or backticks (`).
let space = ' '           // an empty space string
let firstName = 'Naveen'
let lastName = 'Rape'
let country = 'India'
let city = 'Mumbai'
let language = 'JavaScript'
let job = 'SDE'
let quote = "The saying,' Seeing is Believing' is not correct in 2023."
let quotWithBackTick = `The saying,' Seeing is Believing' is not correct in 2020.`


String constructor
  • It is also possible to create a string object using the String() constructor. It is used to create a string object. It takes one argument, which is converted to a string.

let fullName = firstName + space + lastName;
// concatenation, merging two strings together.

console.log(fullName);

Javascript String Format
  • String formatting is a way to format a string using placeholders. It is used to insert values into a string.
  • Backticks allow us to format a string and embed any javascript expression into the javascript string, by wrapping it in `${...}`
  • The expression inside `${...} will be evaluated and output will be returned.

let sum = `10 + 15 = ${10+15}`;
console.log(sum);

let firstName = 'John';
let secondName = 'ram';
let fullName = ` your firstName is
${firstName} and secondName is ${secondName}`;
console.log(fullName)


Multiline String
  • A multiline string is a string that spans multiple lines.
  • The easiest way to create a multiline string is by using backticks.

let program = `Languages:
  * HTML
  * CSS
  * Javascript`;
console.log(program);


Length Of String In Javascript
  • To get the length of a string we have a property called length. It returns the number of characters in the string.


let str1 = "javascript";
console.log(str1.length);


Accessing characters in a string
  • To access a character in a string, you can use square bracket notation just like an array.
  • The index of the character is the position of the character in the string.
  • The first character has an index 0, and the second character has an index 1.

console.log(str1[1]);  // a


Javascript String Concatenation
  • Concatenation is the addition of 2 or more strings into a single string.
  • The string can be concatenated using the + operator between two different strings.

let str1 = "hello";
let str2 = "welcome";

let concat = str1 + str2;

console.log(concat);


Escape Character in Javascript
  • Sometimes you need to show quotes (" or ') in texts but when you write extra quotes in the string then Javascript gets confused for where the string ends.
  • "The color of "ocean" is Blue."
  • The above string will be chopped at "Color of ". And will also cause an error Uncaught SyntaxError: unexpected token: identifier, because javascript identifies string end at 2nd occurrence of the double quote and the next character becomes meaningless for it.
  • To solve the above problem we need to escape quotes using the backslash escape character ( \ ) in the string.


\n: new line
\t: Tab, means 8 spaces
\\: Back slash
\': Single quote (')
\": Double quote (")



let ocean = "Color of \"ocean\" is Blue.";
 
// Output
console.log(ocean);


  • Backslash character ( \ ) is an escape character that is used to escape the character which has a special meaning, like a single quote, double quote, backtick, etc.
String Methods List


1.  charAt()

2.  charCodeAt()

3.  concat()

4.  endsWith()

5.  includes()

6.  indexOf()

7.  lastIndexOf()

8.  match()

9.  matchAll()

10. repeat()

11. replace()

12. replaceAll()

13. search()

14. slice()

15. split()

16. startsWith()

17. substr()

18. substring()

19. toLowerCase()

20. toUpperCase()

21. toString()

22. trim()

23. valueOf()


* length *
  • The string *length* method returns the number of characters in a string including empty space.

let js = 'JavaScript'

console.log(js.length)   // 10

let firstName = 'Naveen'

console.log(firstName.length)  // 6


*toUpperCase()*
  • this method changes the string to uppercase letters.

let string = 'JavaScript'

console.log(string.toUpperCase())     // JAVASCRIPT


*toLowerCase()*
  • this method changes the string to lowercase letters.

let string = 'JavasCript'

console.log(string.toLowerCase())     // javascript


*substr()*
  • It takes two arguments, the starting index and number of characters to slice.

let string = 'JavaScript'

console.log(string.substr(4,6))    // Script


*substring()*
  • It takes two arguments, the starting index and the stopping index but it doesn't include the character at the stopping index.
*split()*
  • The split method splits a string at a specified place.

let string = 'Learn JavaScript'

// Changes to an array -> ["Learn JavaScript"]
console.log(string.split())    
// Split to an array at space -> ["Learn", "JavaScript"]
console.log(string.split(' '))

let firstName = 'Naveen'

// Change to an array - > ["Naveen"]
console.log(firstName.split())    
 // Split to an array at each letter ->  ["N", "a", "v", "e", "e", "n"]
console.log(firstName.split(''))

let countries = 'Finland, Sweden, Norway, Denmark, and Iceland'

// split to any array at comma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(','))  
 //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
console.log(countries.split(', '))


 *trim()*
  •  Removes trailing space in the beginning or the end of a string.

let string = '   learn JavaScript   '

console.log(string)
console.log(string.trim(' '))


*includes()*
  • It takes a substring argument and it checks if a substring argument exists in the string. 
  • includes() returns a boolean. If a substring exists in a string, it returns true, otherwise it returns false.

let string = 'JavaScript'

console.log(string.includes('Java'))     // true
console.log(string.includes('Script'))   // true
console.log(string.includes('script'))   // false
console.log(string.includes('java'))     // false
console.log(string.includes('Java'))     // true


*replace()*
  • takes as a parameter the old substring and a new substring.

Syntax: string.replace(oldsubstring, newsubstring)



let string = 'JavaScript'
console.log(string.replace('JavaScript', 'Python')) // Python

let country = 'india'
console.log(country.replace('india', 'Love'))       // Love


*charAt()*
  • Takes the index and returns the value of that index

Syntax: string.charAt(index)



let string = 'JavaScript'
console.log(string.charAt(0))        // v

let lastIndex = string.length - 1
console.log(string.charAt(lastIndex)) // t


*charCodeAt()*
  • Takes the index and returns the char code (ASCII number) of the value at that index

Syntax: string.charCodeAt(index)



let string = 'JavaScript'
console.log(string.charCodeAt(3))        // D ASCII number is 97

let lastIndex = string.length - 1
console.log(string.charCodeAt(lastIndex)) // t ASCII is 116


*indexOf()*
  • Takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1

Syntax: string.indexOf(substring)



let string = 'JavaScript'

console.log(string.indexOf('J'))          // 0
console.log(string.indexOf('a'))          // 4
console.log(string.indexOf('JavaScript')) // 0
console.log(string.indexOf('Script'))     // -1
console.log(string.indexOf('script'))     // 4


*lastIndexOf()*
  • Takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1

//syntax
string.lastIndexOf(substring)



let string = 'I love JavaScript. If you do not love JavaScript
what else can you love.'

console.log(string.lastIndexOf('love'))       // 67
console.log(string.lastIndexOf('you'))        // 63
console.log(string.lastIndexOf('JavaScript')) // 38


*concat()*
  • it takes many substrings and joins them.

//Syntax
string.concat(substring, substring, substring)



let string = 'Love'
console.log(string.concat( " JavaScript")) // Love JavaScript

let country = 'Love'
console.log(country.concat(" India")) // Love India


*startsWith*
  • it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).

//syntax
string.startsWith(substring)



let country = 'India'

console.log(country.startsWith('Ind'))   // true
console.log(country.startsWith('ind'))   // false
console.log(country.startsWith('India'))  //  true


*endsWith*
  • it takes a substring as an argument and it checks if the string ends with that specified substring. It returns a boolean(true or false).

syntax: string.endsWith(substring)



let country = 'Finland'

console.log(country.endsWith('land'))         // true
console.log(country.endsWith('fin'))          // false
console.log(country.endsWith('Fin'))          //  false


*search*
  • it takes a substring as an argument and it returns the index of the first match. The search value can be a string or  a regular expression pattern.

syntax: string.search(substring)



let string = 'I love JavaScript. If you do not love JavaScript
what else can you love.'
console.log(string.search('love'))          // 2
console.log(string.search(/javascript/gi))  // 7


*match*
  • it takes a substring or regular expression pattern as an argument and it returns an array if there is a match if not it returns null. Let us see what a regular expression pattern looks like. It starts with / sign and ends with / sign.

// syntax
string.match(substring)



let string = 'I love JavaScript. If you do not love
JavaScript what else can you love.'
console.log(string.match('love'))


*repeat()*
  • it takes a number as an argument and it returns the repeated version of the string.

string.repeat(n)



let string = 'love'
console.log(string.repeat(10))
// lovelovelovelovelovelovelovelovelovelove


JavaScript Comments

 JavaScript Comments

  • JavaScript comments are hints that a programmer can add to make their code easier to read and understand. 
  • They are completely ignored by JavaScript engines.

There are two ways to add comments to code:

  • // - Single Line Comments
  • /* */ -Multi-line Comments

Single Line Comments

  • In JavaScript, any line that starts with // is a single-line comment.


    let firstName = "ram";

    // printing name on the console
    console.log("Hello " + firstName);

Multi-line Comments

  • In Javascript, any text between /* and */ is a multi-line comment


    /* The following program contains the source code for
    For the they cannot move. The player controlling the his disposal.
    */

Pseudo-classes

 




What are Pseudo-classes?

A pseudo-class is used to define a special state of an element.

For example, it can be used to:

  • Style an element when a user mouses over it
  • Style visited and unvisited links differently
  • Style an element when it gets focus

The syntax of pseudo-classes:


  selector:pseudo-class {
    property: value;
  }

Interactive states

  • pseudo-classes apply due to an interaction a user has with your page

:hover

  • For example: if the user hovers the mouse on the button then the style of the button changes.

:active

  • if the user clicks on the button then the style of the button should be in an active state.

:visited

  • if a user has already visited then it will show the visited state.

:focus, :focus-within, and :focus-visible 

  • If an element can receive focus—like a <button> you can react to that state with the : focus pseudo-class.

:target

  • :target pseudo-class selects an element that has an id matching a URL fragment. Say you have the following HTML:

<article id="content">

</article>

#content:target {

background: yellow;

}

Order matters:

  • If you define a  :visited style, it can be overridden by a link pseudo-class with at least equal specificity. Because of this, it's recommended that you use the LVHA rule for styling links with pseudo-classes in a particular order: :link,  :visited,  :hover,  :active.
    • a:link {}
    • a:visited {}
    • a:hover {}
    • a:active {}

:first-child and:last-child 
  • If you want to find the first or last item, you can use :first-child and :last-child. These pseudo-classes will return either the first or last element in a group of sibling elements.

:only-child
  • You can also select elements that have no siblings, with the :only-child pseudo-class.

:first-of-type and :last-of-type

  • You can select the :first-of-type and :last-of-type which at first, look like they do the same thing as :first-child and :last-child, but consider this HTML:


<div class="my-parent">
<p>A paragraph</p>
<div>A div</div>
<div>Another div</div>
</div>

.my-parent div:first-child {
color: red;
}

  • No elements would be colored red because the first child is a paragraph and not a div. The :first-of-type pseudo-class is useful in this context.

.my-parent div:first-of-type {
color: red;
}
  • Even though the first <div> is the second child, it is still the first of type inside the .my-parent element, so with this rule, it will be colored red.

:nth-child and :nth-of-type 

  • You're not limited to first and last children and types either. The :nth-child and :nth-of-type pseudo-classes allow you to specify an element that is at a certain index. The indexing in CSS selectors starts at 1.