JavaScript Code Examples: Types, Values, and Variables

Primitive Types

  • number
  • string
  • boolean
  • bigint
  • symbol
  • null
  • undefined

String

Multiple line strings

let multipleLineStr = `hello
world
`;
// or
let multipleLineStr2 = 'hello\n'+
'world';
// or
let multipleLineStr3 = 'hello\n\
world';

Remove HTML tags from a string

let htmlStr = "<div><a href='baidu.com'>test</a></div>";
htmlStr = htmlStr.replace(/<\/?[^>]+(>|$)/g, "");
console.log(htmlStr) // test

Replace newline with <br>

let str = `hello
world
JS`;
str.replace(/(\r|\n|\r\n)/g, "<br>");
// or
str.replaceAll("\r", "<br>").replaceAll("\n", "<br>").replaceAll("\r\n", "<br>");

Reverse string

let s = 'Hello';
// ASCII characters
s.split("").reverse().join(""); // 'olleH'

let s = '😀😂';
// supports UTF-16 or other multi-byte characters
[...s].reverse().join(""); // '😂😀'

Date Object

date to timestamp

const timestamp = new Date().getTime();

timestamp to date

const date = new Date(timestamp)

Type Check

Check null or undefined

value == null

Check undefined

typeof value === 'undefined'

Check null

value === null

Check string type

typeof value === 'string' || value instanceof String

Check number type

typeof value === 'number'

Check object or JSON object

typeof json === "object" && !Array.isArray(value)

Check array or JSON array type

let value = [1, 2, 3];
typeof value === "object" && Array.isArray(value);

Check date object type

let date = new Date();
Object.prototype.toString.call(date) === '[object Date]'

Check function

let obj = ()=>{ console.log("I'm a arrow function") };
typeof obj === 'function'

Type Format

String Format

String format

var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;
let resolution = `your screen resolution is ${width} * ${height}`

String Format with regular expressions

let str = 'My Name is ${name}. His name is ${name}';
let replacement = "John";
str.replace(/${\w}/, replacement);

Add leading zero

let date = 1;
let totalLenght = 2;
let result = String(date).padStart(totalLength, '0'); // '01'
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}

Number Format

let num = 34.7698;
let numFixed = num.toFixed(2);

Date Format

using slice

// date object to UTC datetime string yyyy/MM/dd HH:mm:ss
const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
// date object to local time string yyyy/MM/dd HH:mm:ss
const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

Using date object properties

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;

Type Conversion

Number to String

let num = 1;
let reslut = num.toString() // '1'
let num = 1;
let reslut = num + ''; // '1'

String to Number

  • parseInt(string, radix)
  • Number(string)
let s = "1";
let reslut = parseInt(s); // 1
let s = "1";
let reslut = Number(s); // 1

String to Float Number

  • parseFloat()

Deep Copy

Using JSON.stringify() and JSON.parse()

  • Pros: deep copies nested objects
  • Cons: doesn’t copy functions
let clone = JSON.parse(JSON.stringify(object));

Using Object.assign()

  • Pros: copies the immediate members of an object—including functions.
  • Cons: doesn’t deep copy nested objects
let clone = Object.assign({}, object);

Using spread operator

  • Pros: simple syntax, the preferred way to copy an object
  • Cons: doesn’t deep copy nested objects
const clone = {...object}

Using lodash

  • Pros: clones nested objects including functions
  • Cons: adds an external dependency to your project
var clone = _.cloneDeep(object);