top of page
Writer's pictureCodersarts AI

JavaScript Strings and Numbers Tutorial

JavaScript Strings

  • JavaScript strings are used for storing and manipulating text.

  • A JavaScript string is zero or more characters written inside quotes.

  • Single or double quotes can be used.

  • Quotes can be used inside a string, as long as they don't match the quotes surrounding the string.

Example:


String Length

  • To find the length of a string, use the built-in length property.

  • The length property returns the length of a string.

Example:


Escape Character


The backslash (\) escape character turns special characters into string characters:


Code Result Description

  • \' ' Single quote

  • \" " Double quote

  • \\ \ Backslash

The sequence \"  inserts a double quote in a string.


Example:

Six other escape sequences are valid in JavaScript.

Code Result

  • \b Backspace

  • \f Form Feed

  • \n New Line

  • \r Carriage Return

  • \t Horizontal Tabulator

  • \v Vertical Tabulator

Note:- The 6 escape characters above were originally designed to control typewriters, teletypes, and fax machines. They do not make any sense in HTML.


Breaking Long Code Lines

  • For best readability, programmers often like to avoid code lines longer than 80 characters.

  • If a JavaScript statement does not fit on one line, the best place to break it is after an operator.

  • You can also break up a code line within a text string with a single backslash.

Example:

Note:- The \ method is not the preferred method. It might not have universal support. Some browsers do not allow spaces behind the \ character.


A safer way to break up a string, is to use string addition.


Example:

Note:- You cannot break up a code line with a backslash.


Strings Can be Objects


Normally, JavaScript strings are primitive values, created from literals:

var firstName = "John";

But strings can also be defined as objects with the keyword new:

var firstName = new String("John");

Example:

Note:-

  • Don't create strings as objects. It slows down execution speed.

  • The new keyword complicates the code. This can produce some unexpected results.


  • When using the == operator, equal strings are equal.

  • When using the === operator, equal strings are not equal, because the === operator expects equality in both type and value.

  • Or even worse. Objects cannot be compared.

Example:

Note:- Comparing two JavaScript objects will always return false.


JavaScript String Methods


String methods help you to work with strings.


String Methods and Properties


Primitive values, like "Hello There", cannot have properties or methods (because they are not objects).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.


String Length


The length property returns the length of a string.


Example:


Finding a String in a String


The indexof() method returns the index of (the position of) the first occurrence of a specified text in a string:


Example:

  • JavaScript counts positions from zero.

  • 0 is the first position in a string, 1 is the second, 2 is the third ...

The lastIndexof() method returns the index of the last occurrence of a specified text in a string.


Example:

Note:-

  • Both indexof() and lastIndexof() return -1 if the text is not found.

  • Both methods accept a second parameter as the starting position for the search:

  • The lastIndexof() methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15, the search starts at position 15, and searches to the beginning of the string.


Searching for a String in a String


The search() method searches a string for a specified value and returns the position of the match.


Example:


Extracting String Parts


There are 3 methods for extracting a part of a string:

  • slice(start, end)

  • substring(start, end)

  • substr(start, length)


The slice() Method

  • slice() extracts a part of a string and returns the extracted part in a new string.

  • The method takes 2 parameters: the start position, and the end position (end not included).

Example:

Note:-

  • JavaScript counts positions from zero. First position is 0.

  • If a parameter is negative, the position is counted from the end of the string.

  • If you omit the second parameter, the method will slice out the rest of the string.


The substring() Method

  • substring() is similar to slice().

  • The difference is that substring() cannot accept negative indexes.

Example:

If you omit the second parameter, substring() will slice out the rest of the string.


The substr() Method

  • substr() is similar to slice().

  • The difference is that the second parameter specifies the length of the extracted part.

Example:

  • If you omit the second parameter, substr() will slice out the rest of the string.

  • If the first parameter is negative, the position counts from the end of the string.


Replacing String Content


The replace() method replaces a specified value with another value in a string:


Example:


  • The replace() method does not change the string it is called on. It returns a new string.

  • By default, the replace() method replaces only the first match.

  • By default, the replace() method is case sensitive.

  • To replace case insensitive, use a regular expression with an /i flag (insensitive).

  • Note that regular expressions are written without quotes.

  • To replace all matches, use a regular expression with a /g flag (global match).


Converting to Upper and Lower Case


A string is converted to upper case with toUpperCase().


Example:

A string is converted to lower case with toLowerCase().


Example:


The concat() Method


concat() joins two or more strings:


Example:

  • The concat() method can be used instead of the plus operator. These two lines do the same:

  • All string methods return a new string. They don't modify the original string.

  • Formally said: Strings are immutable: Strings cannot be changed, only replaced.


String.trim()


The trim() method removes whitespace from both sides of a string.


Example:

  • The trim() method is not supported in Internet Explorer 8 or lower.

  • If you need to support IE 8, you can use replace() with a regular expression instead:

  • You can also use the replace solution above to add a trim function to the JavaScript String.prototype.


JavaScript Numbers


JavaScript has only one type of number. Numbers can be written with or without decimals.


Example:

Extra large or extra small numbers can be written with scientific (exponent) notation.


JavaScript Numbers are Always 64-bit Floating Point


Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:


Value (aka Fraction/Mantissa) Exponent Sign

52 bits (0 - 51)  11 bits (52 - 62) 1 bit (63)


Precision

  • Integers (numbers without a period or exponent notation) are accurate up to 15 digits.

  • The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate.


Adding Numbers and Strings

  • JavaScript uses the + operator for both addition and concatenation.

  • Numbers are added. Strings are concatenated.

  • If you add a string and a number, the result will be a string concatenation.

Example:


Numeric Strings


JavaScript strings can have numeric content:

var a = 100;         // a is a number var b = "100";       // b is a string

JavaScript will try to convert strings to numbers in all numeric operations.

JavaScript allows the division(/), multiplication(*) and substraction(-) on strings, but does not support addition(+).


NaN - Not a Number


  • NaN is a JavaScript reserved word indicating that a number is not a legal number.

  • Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number).

Example:

  • However, if the string contains a numeric value , the result will be a number.

  • You can use the global JavaScript function isNaN() to find out if a value is a number.

  • Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN.

  • NaN is a number: typeof NaN returns number.


Infinity


Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.


Example:

  • Division by 0 (zero) also generates Infinity

  • Infinity is a number: typeof Infinity returns number.


Hexadecimal


JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.


Example:

  • By default, JavaScript displays numbers as base 10 decimals.

  • But you can use the to String() method to output numbers from base 2 to base 36.

  • Hexadecimal is base 16. Decimal is base 10. Octal is base 8. Binary is base 2.


Numbers Can be Objects

Normally JavaScript numbers are primitive values created from literals:

var x = 123;

But numbers can also be defined as objects with the keyword new:

var y = new Number(123);


JavaScript Number Methods


Number methods help you work with numbers.


Number Methods and Properties

  • Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects).

  • But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

The toString() Method

  • The toString() method returns a number as a string.

  • All number methods can be used on any type of numbers (literals, variables, or expressions):

Example:


Converting Variables to Numbers

  • There are 3 JavaScript methods that can be used to convert variables to numbers:

  • The Number() methodThe parseInt() methodThe parseFloat() method

  • These methods are not number methods, but global JavaScript methods.


Global JavaScript Methods


JavaScript global methods can be used on all JavaScript data types.


These are the most relevant methods, when working with numbers.


Method Description

  • Number() Returns a number, converted from its argument.

  • parseFloat() Parses its argument and returns a floating point number

  • parseInt() Parses its argument and returns an integer


The Number() Method


Number() can be used to convert JavaScript variables to numbers:


Example:

If the number cannot be converted, NaN (Not a Number) is returned.


The parseInt() Method


parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:


Example:



Number Properties


Property Description

  • MAX_VALUE Returns the largest number possible in JavaScript

  • MIN_VALUE Returns the smallest number possible in JavaScript

  • POSITIVE_INFINITY Represents infinity (returned on overflow)

  • NEGATIVE_INFINITY Represents negative infinity (returned on overflow)

  • NaN Represents a "Not-a-Number" value

Example:


61 views0 comments

Recent Posts

See All

Comments


bottom of page