Skip to content

String

In JavaScript, strings are represented by the primitive string or the String object that wraps it. In JS, strings can be declared either by the ' and " characters, or by the String object constructor, e.g:

const strA = 'first string';
const strB = "second String";
const strC = String('this is new String')

The String object has the length property that returns the number of characters in the object, e.g:

'this will show my chars num'.length // 27

The String object, like the Java String, has many useful methods. Some of them are:

  • concat - connects two or more character strings and returns a new string
  • includes - returns information if one character string contains another
  • indexOf - returns the index number of the first occurrence of the search string. We can also specify from which index to start looking.
  • toLowerCase/toUpperCase - swaps all the letters of a string for lowercase/ uppercase
  • match - finds the first match in the string against the regular expression given
  • repeat - repeats and combines the string given number of times
  • replace - changes the part of a string that matches a regular expression or a string to a given value
  • slice - cuts out a specific piece of string and returns a new string. Requires the index from which it should start. You can also optionally specify the index in which you want to finish cutting, otherwise it will cut the string to the end. In addition, we can use negative indexes, which represent the string index starting from its end.
  • split - divides the string into an array of strings, divided by the given separator
  • trim - removes white marks from the beginning and end of the string

The following JS code shows the use of these methods:

'firstPart'.concat('SecondPart'); // firstPartSecondPart
`ThisIsSda`.includes('IsS'); // true
'LetsLookForAnOO'.indexOf('oo', 1); // 5 
'i\'ll be big'.toUpperCase(); // I'LL BE BIG
'hi5FromSDA'.match('[1-9]'); // ["5"]
'we will '.repeat(3) + 'rock you' // we will we will we will rock yo
'L3ts r3place three'.replace('3', 'e'); // Lets r3place three
'This is quite a long sentence'.slice(10); // ite a long sentence
'This is quite a long sentence'.slice(-5, -1); // tenc
'Lets split this sentence to array of words'.split(' '); // ["Lets","split","this","sentence","to","array","of","words"]
'  RemoveWhitespaces \t '.trim() // RemoveWhitespaces