Submodule 6.3: JavaScript data types

Some of Number and String methods

String methods

JavaScript also has String methods. These methods are very useful when working with strings.

  • String length: .length. This gives us the length of a string which means how many characters we have.
  • indexOf() . This gives us the position of the first occurrence of a specified text or symbol in a string, starting the counting from 0. If there are no results found, returns -1.
  • Slice(). We use this method when we want to extract a particular part of a string. We specify the start and end position of the string we want to extract. The counting starts from zero. If you use positive numbers, then the counting starts from the beginning whereas if we use negative values it starts from the end.
  • Substring(). This method is similar to slice() but it doesn’t accept negative values. In Substring() we specify only the start position. The second value represents the length of the string that we want to extract.

var str = "HTML, CSS, JavaScript";
var sln = str.length; /* 21 */
var pos = str.indexOf("C"); /* 6 */
var res = str.slice(6, 9); /* CSS */

Number methods

JavaScript has Number Methods which are used to convert variables to numbers.
Some examples of Number Methods are:

  • parseInt(). These coverts a number or a string to an integer.
  • parseFloat().These coverts a number or a string to a floating point number.
  • toString() . This converts a number to a string.
  • toPrecision(). This converts a number to a string and returns it with the length we have specified. For example 7.89 toPrecision(2) gives 7.9.

Also, JavaScript has Math operators which are used to perform mathematical tasks.
Examples:

  • Math.random(). This gives us a random number between [0,1).
  • Math.sqrt(). This gives us the square root of a number.
var a = 12.345;
var x = a.toPrecision(3); /* 12.3 */
var y = Math.sqrt(16); /* 4 */
var z = Math.random()*10; /* */
var randomInt = parseInt(z) /* an integer between 0 and 9 */

Exercise

  1. Open your editor, create a new file and save it as exersice06.3.03.html in the folder "Exercises".
  2. Copy the below code and paste it into the new file.
  3. Save the file. You have your HTML page with the Number and String methods. You can experiment on this!

Code: