Wednesday, September 30, 2020

JS Strings | Numbers

Strings are collection of characters stored within quotes (double or single). Strings can have lower case, upper case, special characters or numbers within quotes. Strings can store data, like name, email id, age etc. Default datatype for input, select, textarea value is always a string. 

In JavaScript, Strings are declared inside double quotes "" or single quotes ''. Strings started with double quotes should be closed by double quote and same strings started with single quote should be closed by single quote. Both var x="hello" and var x='hello' are same in javascript.

Backslash, i.e. \ is used inside strings to ignore character. For exp var x="abc\"pqr";

Example 

  var x="Beta Labs";    // string;

 var y='Beta Labs';    // string;
 var z=`Beta Labs`;    // template literal in ES6
 var i="9";            // string
 var j='9';            // string


Template Literals

ES6 introduced Template Literals or Template Strings in JavaScript by using back-tick or grave characters. To insert a placeholder variable in template literal, use ${expression} inside.

var x=3;
var y=5;

console.log(`sum of ${x} and ${y} is ${x+y}`);  //ES6
console.log("sum of " + x + " and " + y + " is " + (x+y));  //ES5

// returns "sum of 3 and 5 is 8"

String Methods and Properties

Primitive values, like "John Doe", cannot have properties or methods (because they are not objects). Properties are information about that string. Properties are checked using Dot notation (.) or brackets [ ] with property name in quotes. See example 

String.length property shows the number of characters in string.

var x = 'hello js';
x.length; // 8

String length property is immutable, means if length of string is 8 and we assign string.length to 10, it will still return 8. See example

var x = 'hello js';

x.length; // 8

x.length = 10;

x.length; // 8

x.length = 2;

x.length; // 8 


Empty String: An empty string is the string with length equals to zero.

var x = '';
x.length; // 0

String Methods

JavaScript Methods are build in functions used to perform an action to strings. All methods are called by method name and then parenthesis. Parameters are passed inside parenthesis if required. For exp, x.age is property, but x.getAge() is a method. 

indexOf: This method returns index of first matched substring. The return value of indexOf() methods is always a number.

If substring is not found, it will return -1.

var x = 'Beta Labs';


x.indexOf('B'); // return 0;

x.indexOf('e'); // return 1;

x.indexOf('f'); // return -1;

lastIndexOf: This method returns index of last matched substring. The return value of lastIndexOf() method will also be number.

If substring is not found, it will return -1.

var x = 'beta labs';

x.indexOf('b'); // return 0;

x.lastIndexOf('a'); // return 6;

x.lastIndexOf('e'); // return 1;

concat: concat() method is used to concatenate or merge two strings into one. The second string should be passed as argument.

var x = 'beta';
var y = 'labs';

x.concat(y); // return betalabs 

+ operator can also concat two strings in javascript.

var x = 'beta';
var y = 'labs';

x + y; // return betalabs

charAt: charAt() method return character at given index in argument.

var x = 'betalabs';

x.charAt(0); // return b

x.charAt(1); // return e

x.charAt(x.length - 1); // return s

x.charAt(x.length); // return ""

charCodeAt: charCodeAt() method return ASCII code of character at given index in argument.

var x = 'betalabs';

x.charCodeAt(0); // return 98

x.charCodeAt(1); // return 101


 toUpperCase: toUpperCase() method convert all lowercase characters to uppercase.

 var x = 'betlabs';


x.toUpperCase(); // return "BETALABS"

toUpperCase method only return string in uppercase, but value of x will remain same, .ie. lowercase

 

toLowerCase: toLowerCase() method convert all uppercase characters to lowercase.

var x = 'Beta Labs';

x.toLowerCase(); // return "beta labs"

substr : substr() method return substrings from index (first argument ) to given no of characters (second argument). First argument is always index and second is no of characters. If second argument is missing, it will return substrings after first index. See examples

var x = 'betalabs';

x.substr(2); // return "talabs"

x.substr(4); // return "labs"

x.substr(04); // return "beta"

x.substr(22); // return "ta"

x.substr(44); // return "labs"

For IE8 and below, use substring

 

search: search() method search for a matched pattern between string and regular expression and return index of matched pattern.

var x = 'beta labs';

x.search('t'); // return 0

x.search('T'); // return -1

x.search(/\s/);

// return 4, i.e, white space found at 4th index

x.search(/\d/);

// return -1, i.e, no digit found

To know more about regular expressions, click here. JavaScript Regular Expressions

 

trim: trim() method trim extra whitespace from beginning and end.

var x = ' beta labs ';

x.trim(); // return "beta labs"

replace: replace() method is used to replace a single or multiple characters with a new characters. The first argument is replaced character, and second is replacing one.

var x = 'beta labs';


x.replace('b''B'); // return "Beta labs"

x.replace('labs''LABS'); // return "beta LABS"

x.replace(' ''-'); // return "beta-labs"

split: split() method splits a string to array

var x = 'beta labs';

x.split(' '); // return ["beta","labs"]
 

 

    

JavaScript Numbers can be integers (example 3) or whole numbers (example 3.14). JavaScript Numbers can perform addition, subtraction, multiplication, division and Modulus. Thus all arithmetic operations can be performed using JavaScript numbers. JavaScript Supports all numbers systems, including Binary, Octal, Decimal, and Hexadecimal numbers. A number starting with 0 is by-default octal in JavaScript. For example, 010 is 8 in JavaScript.

  •  var is used to declare numbers in JavaScript.
  • For fixed numbers, const is also used.
  • typeof operator can check datatype of numbers.

var a = 3// number;
var b = 3.6// number with decimal;
var c = 2e3// exponential number (2000)
var d = 0xa// number in hexadecimal
var e = 010// number in octal
var f = 0o10// number in octal
var g = 0b100// number in binary
var h = NaN// not a number
var i = Infinity// number more than 10308

 

Binary, Octal, Decimal and Hexadecimal Numbers

Here is a comparison of Binary numbersOctal numbersDecimal numbers and Hexadecimal numbers.


Number

Binary
(0-1)
(2 bit)

Octal
(0-7)
(8 bit)

Decimal
(0-9)
(10 bit)

Hexadecimal
(0-f)
(16 bit)

0

0

0

0

0

1

1

1

1

1

2

10

2

2

2

8

1000

10

8

8

10

1010

12

10

a

15

1111

17

15

f

16

10000

20

16

10


Numbers Method: Numbers Methods are used to convert a number to string, exponential, precision and fixed. Here are number methods with examples.

JavaScript Number Methods

Method

use

Example

toString()

convert number to string.

var x=6;
x.toString()="6";

toLocalString()

convert number to local string.

var x=6;
x.toLocalString()="6";

toExponential()

convert decimal to exponential notation.

var x=6;
x.toExponential()="6e+0";

toPrecision(1)

convert number to Precise .

var x=1.23456;
x.toPrecision(1)="1";

toPrecision(2)

convert decimal to precision 2 .

var x=1.23456;
x.toPrecision(2)="1.2";

toPrecision(3)

convert decimal to precision 3 .

var x=1.23456;
x.toPrecision(3)="1.23";

toFixed()

to convert a number to string with fixed decimal value

var pi=3.1416;
pi.toFixed(); // "3"
pi.toFixed(1); // "3.1"
pi.toFixed(2); // "3.14"
pi.toFixed(3); // "3.142"

String to Number in JavaScript: JavaScript variables can be strings or numbers. Like var x="5" is string, but var y=5 is number. Both can be used in arithmetic operations. Except addition, all arithmetic operations are possible with x and y. Functions to convert string to number.

  1. Number Function

  2. parseint Function
  3. parsefloat Function

Number Function: Number Function can convert string to numbers. Number Function can convert both floating/decimal and non-floating/integers. But if a string contains string character like alphabets or special character, number function will return NaN.

var a = '100';
var b = '100.5';
var c = '100px';
var d = 'abc100';

Number(a); //100
Number(b); //100.5
Number(c); //NaN - Not a Number
Number(d); //NaN - Not a Number

 


parseInt Function

parseInt Function can convert string to numbers, but non-floating/integers values only. parseInt can also convert binary, octal and hexadecimal to decimal numbers.

var a = '100';
var b = '100.5';
var c = '100px';
var d = 'abc100';

parseInt(a); //100
parseInt(b); //100
parseInt(c); //100
parseInt(d); //NaN - Not a Number

parseInt function is also used to convert decimal to binarydecimal to octal and decimal to hexadecimal numbers. To do this, pass second parameter in parseInt function as 2 for binary8 for octal, and 16 for hexadecimal. See example.


var a = '100';
var b = '100.5';
var c = '100px';
var d = 'abc100';

parseInt(a); //100
parseInt(b); //100
parseInt(c); //100
parseInt(d); //NaN - Not a Number

 
parseFloat Function
parseFloat Function can convert string to numbers, floating/decimals and non-floating/intergers both. parseFloat can also convert binary, octal and hexadecimal to decimal numbers.

var a = '100';
var b = '100.5';
var c = '100px';
var d = '100.5px';
var e = 'abc100';

parseFloat(a); //100
parseFloat(b); //100.5
parseFloat(c); //100
parseFloat(d); //100.5
parseFloat(e); //NaN - Not a Number

isNaN, is Not a Number Function

JavaScript isNaN function returns a boolean value. For example, isNaN("2") is false and isNaN("a") is true. Even isNaN(NaN) is also true.


isNaN(NaN); // returns true
isNaN(1); // returns false
isNaN('1'); // returns false
isNaN('a'); // returns true
isNaN('2a'); // returns true

isFinite

isFinite function tells whether a number is finite or not. In JavaScript, number less than 1e308 or 1e+308 are finite numbers. Numbers greater than 1e308 are Infinite, for example, 2e308 and more are infinite numbers in JavaScript.


isFinite(Infinity); // false
isFinite(2e308); // false
isFinite(1e308); // true
isFinite(1e307); // true
isFinite(123); // true

- Never starts a number with 0.
- Floating numbers can have maximum 16 characters after decimal.
- Binary i.e.0b100 and Octal 0o100 are not supported in all browsers.