Javascript html text formatting

Text formatting

JavaScript’s String type is used to represent textual data. It is a set of «elements» of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it. You can create strings using string literals or string objects.

String literals

Hexadecimal escape sequences

Unicode escape sequences

Unicode code point escapes

New in ECMAScript 6. With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to 0x10FFFF . With simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same. See also String.fromCodePoint() or String.prototype.codePointAt() .

'\u' // the same with simple Unicode escapes '\uD87E\uDC04'

String objects

var s = new String("foo"); // Creates a String object console.log(s); // Displays: < '0': 'f', '1': 'o', '2': 'o'>typeof s; // Returns 'object'

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal. You should use string literals unless you specifically need to use a String object, because String objects can have counterintuitive behavior. For example:

var s1 = "2 + 2"; // Creates a string literal value var s2 = new String("2 + 2"); // Creates a String object eval(s1); // Returns the number 4 eval(s2); // Returns the string "2 + 2"

A String object has one property, length , that indicates the number of characters in the string. For example, the following code assigns x the value 13, because «Hello, World!» has 13 characters:

var mystring = "Hello, World!"; var x = mystring.length;

A String object has a variety of methods: for example those that return a variation on the string itself, such as substring and toUpperCase . The following table summarizes the methods of String objects.

Читайте также:  Style display none in php

Methods of String

Multi-line template strings

Template strings are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. Template strings are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template strings can contain place holders. These are indicated by the Dollar sign and curly braces ( $ ).

Multi-lines

Any new line characters inserted in the source are part of the template string. Using normal strings, you would have to use the following syntax in order to get multi-line strings:

console.log("string text line 1\n\ string text line 2"); // "string text line 1 // string text line 2"
console.log(`string text line 1 string text line 2`); // "string text line 1 // string text line 2"

Embedded expressions

var a = 5; var b = 10; console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + "."); // "Fifteen is 15 and // not 20."

Now, with template strings, you are able to make use of the syntactic sugar making substitutions like this more readable:

var a = 5; var b = 10; console.log(`Fifteen is $ and\nnot $.`); // "Fifteen is 15 and // not 20."

Internationalization

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for Collator , NumberFormat , and DateTimeFormat objects are properties of the Intl object.

Date and time formatting

The DateTimeFormat object is useful for formatting date and time. The following formats a date for English as used in the United States. (The result is different in another time zone.)

var msPerDay = 24 * 60 * 60 * 1000; // July 17, 2014 00:00:00 UTC. var july172014 = new Date(msPerDay * (44 * 365 + 11 + 197)); var options = < year: "2-digit", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", timeZoneName: "short" >; var americanDateTime = new Intl.DateTimeFormat("en-US", options).format; console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT

Number formatting

var gasPrice = new Intl.NumberFormat("en-US", < style: "currency", currency: "USD", minimumFractionDigits: 3 >); console.log(gasPrice.format(5.259)); // $5.259 var hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec", < style: "currency", currency: "CNY" >); console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五

Collation

The Collator object is useful for comparing and sorting strings. For example, there are actually two different sort orders in German, phonebook and dictionary. Phonebook sort emphasizes sound, and it’s as if “ä”, “ö”, and so on were expanded to “ae”, “oe”, and so on prior to sorting.

var names = ["Hochberg", "Hönigswald", "Holzman"]; var germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk"); // as if sorting ["Hochberg", "Hoenigswald", "Holzman"]: console.log(names.sort(germanPhonebook.compare).join(", ")); // logs "Hochberg, Hönigswald, Holzman"

Some German words conjugate with extra umlauts, so in dictionaries it’s sensible to order ignoring umlauts (except when ordering words differing only by umlauts: schon before schön).

var germanDictionary = new Intl.Collator("de-DE-u-co-dict"); // as if sorting ["Hochberg", "Honigswald", "Holzman"]: console.log(names.sort(germanDictionary.compare).join(", ")); // logs "Hochberg, Holzman, Hönigswald"

Regular expressions

Источник

JavaScript String Format — in 3 Ways

In this article, you are going to learn what is string formatting or string interpolation in JavaScript, different JavaScript string format methods, creating a function to format a string, and how to use string formatting in JavaScript.

1. String Formatting

String formatting is the process of inserting variables into a string. In modern languages generally, it is done by using the curly braces ( <> ). It is also called string interpolation .

Many languages have a built-in string method to format strings, but not all languages have it.

Another famous approach for string formatting is concatenation. It is a process of joining two or more strings together. It is done by using the + operator.

javascript string format

From the above image, you can see that the variables are inserted into the string and called placeholders. The placeholders get replaced with the values of the variables and we can see that the string is formatted.

2. Javascript Format String ( Quick Solution )

For your quick reference, here is the code for string formatting in javascript in 3 different ways.

let name = "John"; let age = 25; let city = "New York"; // 1. Using backticks let str1 = `My name is $. I am $ years old. I live in $.`; console.log(str1); // 2. Using + operator let str2 = "My name is " + name + ". I am " + age + " years old. I live in " + city + "."; console.log(str2); // 3. Using a custom function String.prototype.format = function() < let formatted = this; for (let i = 0; i < arguments.length; i++) < let regexp = new RegExp('\\', 'gi'); formatted = formatted.replace(regexp, arguments[i]); > return formatted; >; let formatted = "Hello ! Welcome to .".format("John", "New York"); console.log(formatted);

For detail explanation, read the article below.

3. String Formatting in JavaScript

In javascript, there is no built-in string formatting function. But there are other ways to format a string.

Here we are going to look at the 3 different methods to format a string in javascript.

  1. Using <> brackets within backticks «
  2. Using + operator
  3. By creating a format function

3.1. Format String Using Backticks

Best way to format a string in javascript is by using backticks « .

To format string backticks wraps the string and the variables are inserted within the backticks wrapped in curly braces <> preceded by a dollar sign $ .

These variables are called placeholders within the string which are replaced with the values of the variables.

// format string javascript let name = "John"; let age = 30; let food = "pizza"; // String formatting using backticks let sentence = `$ is $ years old and likes $`; console.log(sentence); // John is 30 years old and likes pizza

You can run and see the output of the above code all the placeholders are replaced with the values of the variables.

format string javascript backticks

Possible mistake : Make sure that you are using backticks ( ` ) and not single quotes ( ‘ ) or double quotes ( » ).

Within these backticks, any javascript expression is valid and it will be evaluated and replaced with the value of the expression.

You can use variables, functions, and any javascript expression within the backticks.

// arithmetic expression var sum = `$`; console.log(sum); // 4 // function call function fullName(fName, lName) < return `$$`; > console.log(`My full name is $`); // My full name is John Smith // Ternary operator let age = 30; let message = `$= 18 ? "Adult" : "Child">`; console.log(message); // Adult

3.2. Format String Using Plus Operator

Another way to format a string is by using the + operator. This is done by concatenating the string with the variables.

This replaces the variable with the value and concatenates it with the string.

// javascript format string let name = "John"; let age = 30; let food = "pizza"; // String formatting using plus operator let sentence = name + ' is ' + age + ' years old and likes ' + food; console.log(sentence); // John is 30 years old and likes pizza

You can also use javaScript expressions and function calls within the string but you need to be careful because it can lead to unexpected results, also this is not recommended because it is not as readable as the backticks.

// JS format string let age = 30; console.log('You are ' + age > 18 ? 'Adult' : 'Child'); // unexpected result ❌ console.log('Sum of 2 + 2 is ' + 2 + 2); // correct way // using parenthesis console.log('Sum of 2 + 2 is ' + (2 + 2));

3.3. Custom function for String Formatting

As we mensioned earlier that some languages have built-in function to format a string. Like in Python.

Here we are going to create a string method (using prototype) that will be called on string and replace the placeholders with the values of the variables.

Example: ‘Hello . You like ‘.format(name, fruit) or ‘Hello . You like ‘.format(fruit, name)

Example: String.format function

// JS format string String.prototype.format = function () < // store arguments in an array var args = arguments; // use replace to iterate over the string // select the match and check if the related argument is present // if yes, replace the match with the argument return this.replace(//g, function (match, index) < // check if the argument is present return typeof args[index] == 'undefined' ? match : args[index]; >); >; console.log(' is years old and likes '.format('John', 30, 'pizza'));

The above method is made to be part of the string prototype so that it can be used on any string object. You can also use it on any variable which is a string.

Javascript String Format Example

Below is an example of how to use the above methods.

// assigning value var marks = 65; var status = `John => $= 60 ? "Pass" : "Fail">`; console.log(status); // John => Pass

Example: JavaScript expression

// JavaScript expression var numbers = [13, 2, 32, 54, 5]; var biggest = `The biggest number is $`; console.log(biggest); // The biggest number is 54

Similarly, you can use the above mensioned methods on any string object to format it.

Frequency Asked Questions

  1. What is $<> in JavaScript? $<> is a placeholder in JavaScript. It is used to insert the value of a variable or an expression in a string. They are used in template literals « .
  2. How to format a string in JavaScript? As discussed in the article, there are 3 ways to format a string in JavaScript. 1. Using plus operator, 2. Using backticks, 3. Using custom function.
  3. What is the format of string template in JavaScript? The format of string template in JavaScript is `$` or `$` . It is used to insert the value of a variable or an expression in a string.

Conclusions

In web development, we continuously need to format string in javascript. We have discussed 3 different ways for js string format.

By far the best way is to use backticks to format the string.

No matter if you’re looking for this explanation to do your homework or to complete some kind of your working task, we hope that it was clear enough to comprehend. You can order JavaScript assignment help and use their knowledge to deal with your working load if you got stuck and there’s nobody to help you out.

Источник

Оцените статью