Wednesday, December 13, 2017

Some basic JavaScript String concepts

Basic and Best things to know work with JavaScript Strings:

1. String replace

The replace function will help to replace any string operation. It will replace string for the first occurrence only.

So by going with regex its so simple and your quality of code will be good.

let first = " I want to replace first as second , but here first comes in many places";

first.replace(/first/g,"second")

" I want to replace second as second , but here second comes in many places"

2. Template String

In ES6, we have an option to use template string which will give an option to modify the string within it. Example below.


let templateSecond = "I am waiting for you!"
`Hi Monisha ${templateSecond}`
"Hi Monisha I am waiting for you!"

3. Includes

If you want to find whether particular string is available or not in the current string. Use like below

let includeChck ="ABC, DEF, GHI, JKL, MNO"
includeChck.includes("GHI") //Output : true

includeChck.includes("GHIS") //Output : false

4. String to Number


let strToNum = "1234576"
parseInt(strToNum) // Output: 1234576

let str = "123488bcd34"
parseInt(str)    //Output: 123488

Remember if character placed after number it will not consider.

The same thing can apply to parseFloat also.

5. setInterval and setTimeout

While passing function to setInterval and setTimeout do not use string quotes. Use without quotes, so that it can bring better performance.

Else eval function will be executed it makes process time to slow.

//Wrong Format
setInterval('doSomethingPeriodically()', 1000);  
setTimeout('doSomethingAfterFiveSeconds()', 5000);


//Correct Format
setInterval(doSomethingPeriodically, 1000);  
setTimeout(doSomethingAfterFiveSeconds, 5000);