Strings

DevJunctionPoint
0

 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


Tags

Post a Comment

0Comments

Do leave your comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Ok, Go it!
To Top