The method toLocaleString generates a string that displays the contents of an array by converting its elements into strings.
Syntax
array.toLocaleString();
Parameter
array: It is the given array or the source array.
In addition to this, there are two additional parameters that are optional as well.
Locales: A locale is a string that adheres to the BCP 47 language tag standard, which is an IETF code used to specify human languages.
Options: An object that is primarily utilized for handling dates and numbers. These objects encapsulate their configuration properties within themselves.
Return
A string is generated and returned to represent the elements within an array.
JavaScript toLocaleString Example
Let's examine the following examples for improved comprehension:
Example1
Below is a demonstration illustrating the fundamental application of the toLocaleString method.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr=["ram","shyam","Heera"]; // an array is defined.
var str=arr.toLocaleString(); //using array toLocaleString() method
document.write("The array is represented in the string form as: "+str); // This will return the array elements in the form of string.
</script>
</body>
</html>
Output:
The output is shown below:
The array is displayed as a string in the output.
Example2
Here is a sample code snippet demonstrating the usage of the date method in conjunction with the toLocaleMethod.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
const arr = [1, 'a', new Date('08 Jan 1997 17:12:00 UTC')];
const str = arr.toLocaleString('en', {timeZone: "UTC"}); //UTC is the Coordinated Universal Time.
document.write("The converted array elements in string form are: "+str);
</script>
</body>
</html>
Output:
Example3
Implementing the above example on the console.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
const arr = [1, 'a', new Date('08 Jan 1997 17:12:00 UTC')];
const str = arr.toLocaleString('en', {timeZone: "UTC"}); //UTC is the Coordinated Universal Time.
console.log("The converted array elements in string form are: "+str); //on console
</script>
</body>
</html>
Output:
Example4
Demonstrating a scenario where the elements of an array are merged with a specific value to create a new array.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr = ["John","Tom","Mary","Herry","Sheero" ]; //Defining an array
var val = 5; //Intializing the value of val.
var netarr = [ arr,val ]; //Creating a new array that combines both initialized variables.
var str = netarr.toLocaleString(); //Using the method
document.write("The netarr gets converted into string as: "+str); //Converting to string.
</script>
</body>
</html>
Output:
The output comes out as: