JavaScript can be used to create functions that allow you to format strings using HTML descriptors, but many basic formatting features are provided directly by the methods of the string object.
The principle of operation of these string formatting methods is very simple – they simply add the necessary descriptors to the beginning and end of the string.
Other string formatting methods include big(), bold(), italics(), small(), strike(), sub(), and sup(). The sub() and sup() methods are used to format string characters as subscripts and superscripts.
You can also change the font size using the fontsize() method, which gets the font size as a parameter. This parameter can take an integer value ranging from 1 to 7, with 7 being the largest value. The font color can be set using the fontcolor() method, which gets a color parameter represented as a color name or a hexadecimal color value.
The example below uses a file js-format.html however, the described actions are applicable to any file.
<html>
<head>
<title>Formatting string variables</title>
</head>
<body>
<script>
let str = "Formatted text";
document.write(str);
document.write(str.big());
document.write(str.bold());
document.write(str.italics());
document.write(str.small());
document.write(str.strike());
document.write(str.sub());
document.write(str.sup());
</script>
</body>
Результат выполнения js-format.html
Formatted text
Formatted text
Formatted text
Formatted text
Formatted textFormatted text
Formatted text
Formatted text
If the sub() and sup() methods are used to format the entire string, it is quite difficult to determine how much a formatted string differs from a regular one until it can be compared with some other string on a Web page. A more appropriate way to use the sub() method is to construct, for example, the following line.
water = "H" + "2".sub() + "O";This operator creates a string variable named water, which includes the character “H”, the string for the number 2 returned by the sub() method, and the character “O”. In the resulting line, the number is displayed as the subscript of the letter “H”. As a result of this example, the chemical formula of water, H2O, is obtained in accordance with the variable name — water.