GeeKee's Odyssey

GeeKee's Odyssey

String and String Ops.

Photo by Bozhin Karaivanov on Unsplash

String and String Ops.

Special agent much?

gayatri kumar's photo
gayatri kumar
·Jun 26, 2022·

2 min read

Table of contents

  • String Methods
  • String Template Literals

Strings in Js is simply text wrapped in quotes. You can use double or single quotes, just be consistent.

let myName = 'Gayatri';
let myFullName = "Gayatri Kumar";
let friendsName = 'Pabo Shivrav';

In string each character is indexed, and can be accessed individually.

image.png

let name = 'Shivanu';

name[0]  //'S'
name[3]  //'v'
name[-1]  //undefined
name[9]  //undefined as it is out of index

String Methods

To make our lives much easier, Js comes with a set of built-in methods which can be performed on strings. These methods help us search within the string, replace parts of the string, change the case and much more.

let myString = 'WiFi is the bestest dog!'

.length

myString.length; //24

Changing Case

let shout = myString.toUpperCase();
// 'WIFI IS THE BESTEST DOG'

let calm = myString.toLowerCase();
// 'wifi is the bestest dog'

trim()

Removes all the leading and trailing white spaces in a string.

let mood = '      lonely...      '
mood.trim()  //'lonely'

indexOf()

myString.indexOf('the');  //8
myString.indexOf('dog');  //20
myString.indexOf('cat');  //-1 as it is not found

slice

string.slice(start, end)

[start, end) i.e starting index included, ending index not included.

myString.slice(0, 5);  //'WiFi '

//It will slice everything from starting index till the end
myString.slice(5);  //'is the bestest dog!' 

//To easily get last character of sring
myString.slice(-1)  //'!'

replace

string.replace(searchValue, replaceValue)

myString.replace('bestest', 'cutest')
//'WiFi is the cutest dog'

This method only replaces the first instance.

String Template Literals

ES6 has introduces string template literals which makes it easier to combine variables and strings or even add logic in the string. They allow embedded expressions, which will be evaluated and then turned into the resulting string.

Here Back-Ticks are used and not 'quotes'.

`Being ${20 + 50} is like being 20 years old with 50 years of experience`
//Being 70 is like being 20 years old with 50 years of experience

let updateString = `${myString} and the Cutuest!`
//'WiFi is the bestest dog! and the Cutuest!'
 
Share this