Strings¶
In JavaScript, strings are represented by a string
primitive or aString
object that wraps around it. In JS we can declare strings using both the characters '
and "
, or using the constructor of the String
object, e.g.:
const strA = 'first string';
const strB = "second String";
const strC = String('this is new String')
The String
object has a length property that returns the number of characters in the object, e.g.:
'this will show my chars num'.length // 27
Popular methods¶
The String
object, like theString
in Java, has many useful methods. Some of them are:
concat
- concatenates two or more strings and returns a new stringincludes
- returns whether one string contains the otherindexOf
- Returns the index number of the first occurrence of the search string. We can also indicate which index to start looking for.toLowerCase
/toUpperCase
- converts all string letters to lowercase/uppercasematch
- finds the first match in the string against the given regular expressionrepeat
- repeats and concatenates a string the given number of timesreplace
- replaces part of a string matching the regular expression or string with the given valueslice
- cuts the specified piece of string and returns a new string. It requires an index with which to start. You can also optionally specify the index where you want the cut to stop, otherwise it will cut the string to the end. In addition, we can use negative indices that represent the string's index starting from its end.split
- splits a string into an array of strings, divided by the given separatortrim
- removes white space from the beginning and end of a 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