javascript tagged requests and articles

Categorized request examples and articles tagged with [javascript] keyword
How do I send a POST request using JavaScript?
To make an HTTP POST request from a web browser, JavaScript offers two primary methods: the promise-driven fetch() API and the callback-driven XMLHttpRequest object. To send POST requests from Node.js, you can use the native "http" module. To make a POST request with JavaScript Fetch API, you must indicate the HTTP POST method name with the "method" parameter and the POST payload in the "body" parameter. Extra HTTP request headers can be set with the "headers" parameter. In this JavaScript POST request example, we send a POST request to the ReqBin echo URL using the fetch() method. Below are additional examples of sending JavaScript POST requests with XMLHttpRequest object. Click "Execute" to make a JavaScript POST request online and see the result.

How to send Bearer Token with JavaScript Fetch API?
To send a Bearer Token in an Authorization header to a server using the JavaScript Fetch API, you must pass the "Authorization: bearer {token}" HTTP header to the fetch() method using the "headers" parameter. Bearer Token is an encrypted string returned by the server and stored on the user's computer that authenticates the user to access protected resources on the server. You must pass a Bearer Token to the fetch() method for every request you make to a protected resource. In this JavaScript Fetch API Bearer Token example, we send a request with an Authorization header to the ReqBin echo URL using the fetch() method. Click Execute to run the JavaScript Fetch API Bearer Token Authorization Header example online and see the result.

How do I fetch JSON using JavaScript Fetch API?
To fetch JSON from the server using the Fetch API, you need to use the JavaScript fetch() method and then call the response.json() method to get the JSON data as a JavaScript object. The response.json() method reads the data returned by the server and returns a Promise that resolves with a JSON object. If you are expecting a text, call the response.text() method. For some servers, you must also send the "Accept: application/json" header to get the response in JSON format. In this JavaScript Fetch JSON example, we retrieve a JSON from the ReqBin echo URL using the fetch() method. Click Execute to run the JavaScript Fetch JSON Example online and see the result.

How to make a GET request using JavaScript?
To make a GET request with JavaScript, call the fetch() method and provide the target URL. The fetch() uses GET by default if no HTTP method is passed. To send additional HTTP headers to the server with your JavaScript GET request, pass them with "headers" parameters. If you want to include credentials in your GET request, set credentials: "include". For older browsers, you can use the XMLHttpRequest object to make HTTP requests. In this JavaScript GET Request example, we send a request to the ReqBin echo URL using the fetch() method with a custom HTTP header. Below are additional examples of JavaScript GET requests with detailed descriptions. Click "Execute" to run the JavaScript GET Request online and see the result.

How to get a sum of array elements in JavaScript?
To get the sum of array elements in JavaScript, you can use the array.reduce(callback, initialValue) method. The array.reduce() method invokes the callback function once for each array element and passes the result of the callback function call to the next call. The sum of the array elements will be returned as the result of the array.reduce() method. Alternatively, you can find the sum of array elements using a "for" loop. In this JavaScript Array Sum Example, we use the reduce() method to get the sum of the array elements with an initial value. Below you can see more examples of calculating the sum of JavaScript array elements with detailed descriptions. Click Execute to run the JavaScript Array Sum Example online and see the result.

How do I convert object to JSON in JavaScript?
To convert a JavaScript object to JSON, you can use the JSON.stringify(value, replacer, space) method. The JSON.stringify() method serializes objects, arrays, and primitive values into a JSON data string. The optional "replacer" parameter is a function that allows you to alter the behavior of the serialization process, and the optional "space" parameter allows you to create human-readable JSON strings. If you don't pass a "space" parameter, the JSON.stringify() method will output a minified JSON. In this JavaScript Object to JSON example, we serialize the JavaScript object to JSON data string and pretty-print the generated JSON. Click Execute to run the JavaScript Object to JSON Example online and see the result.

How do I join array elements in JavaScript?
To join JavaScript array elements in a string, you can use the array.join(separator) method. The array.join() method takes an array as input and a delimiter as a parameter and returns a string where all array elements are joined into a string using the specified delimiter. By default, array elements are concatenated using a comma "," as a delimiter. The array.join() method does not modify the array. If the method is called on an empty array (the length of the array is zero), then an empty string will be returned. Any array element that has the value "undefined" or "null" will be converted to an empty string. In this JavaScript Join Array Elements into a String Example, we use the array.join() method to join all array elements in a string. Click Execute to run the JavaScript Array Join Example online and see the result.

How do I pretty print JSON in JavaScript?
To pretty-print JSON in JavaScript, you can use the JSON.stringify(obj, replacer, space) method. The third parameter of the JSON.stringify() method specifies the number of spaces to use when outputting the JSON string. If you pass a non-zero number, JSON.stringify() will generate pretty JSON with the specified number of white spaces in the JSON. If you pass 0, then JSON.stringify() will generate minified JSON. You can also pass a string instead of a number, which will be inserted instead of spaces. In this JavaScript Pretty Print JSON example, we use the JSON.stringify() method to print a JavaScript object in a human-readable format. Click Execute to run the JavaScript Pretty Print JSON example online and see the result.

How do I convert JavaScript array to JSON?
To convert a JavaScript array to a JSON data string, you can use the JSON.stringify(value, replacer, space) method. The optional replacer parameter is a function that can alter the behavior of the serialization process. And the optional space parameter is usually used to beautify the resulting JSON by specifying the white space in the output JSON. The JSON.stringify() method serializes arrays, objects, and primitive values into a JSON string. In this JavaScript Array to JSON example, we serialize a JavaScript array into a JSON string using JSON.stringify() method. Click Execute to run the JavaScript Array to JSON Example online and see the result.

How to make requests using XMLHttpRequest in JavaScript?
To make a request using a JavaScript XMLHttpRequest object, you must first create an XMLHttpRequest object and then open the target URL by calling the xhr.open() method. POST data can be sent to the server by passing it to the xhr.send() method. Custom HTTP headers can be added to the request using the xhr.setRequestHeader(). The xhr.onload event will be fired after the XMLHttpRequest object has completed the asynchronous request. An xhr.status value of 200x indicates that the request was successful, 300x indicates a redirect, and 400x and 500x indicate an error. In this JavaScript XMLHttpRequest Request example, we make a request to the ReqBin echo URL. Click Execute to run JavaScript XMLHttpRequest example online and see the result.

How do I convert array to string in JavaScript?
To convert an array to a string in JavaScript, you can use the Array.toString() method. This method returns a string where all array elements are concatenated into a comma-separated string. The Array.toString() method does not change the original array. Calling this method on an empty array results in an empty string. Any array elements that are null or undefined will be converted to an empty string. The Array.toString() method does not accept any parameters. If you need to convert an array to a string with a specific separator, use the Array.join(separator) method. In this JavaScript Array to String example, we use the Array.toString() method to convert an array with elements to a string. More examples of converting an array to a string are listed below. Click "Run" to run the JavaScript toString example online and see the result.

How to send Authorization Credentials with JavaScript Fetch API?
To send authorization credentials using the Fetch API in JavaScript, you need to allow the credentials to be sent to the server by adding the «credential: 'include'» parameter when calling the fetch() method. Default Fetch API requests do not contain user credentials such as cookies and HTTP authentication headers. This is done for security reasons because user authentication data allows JavaScript to act on behalf of the user and obtain private information. If you want to send credentials only to the original domain, use the «credentials: 'same-origin'» parameter. To prevent the browser from sending credentials at all, use the «credentials: 'omit'» option. In this JavaScript Fetch API with Credentials example, we send a request with «credential: 'include'» parameter to the ReqBin echo URL using the fetch() method. Click Execute to run the JavaScript Fetch API with Credentials example online and see the result.

How to send headers with JavaScript Fetch API?
To send HTTP headers to the server using the JavaScript Fetch API, you can pass these headers with the "options" parameter to the fetch(URL, options) method. The headers are passed in the "key: value" format and may override some standard HTTP headers or pass new ones. Not all default HTTP headers can be overridden for Fetch API requests; for example, you can override the Content-Type header, but you cannot override the Content-Length header. In this JavaScript Fetch API Headers example, we send a request with a Content-Type header to the ReqBin echo URL using the fetch() method. Click Execute to run the JavaScript Fetch Headers example online and see the result.

How to stringify a JavaScript object to JSON string?
You can use the JSON.stringify(value, replacer, space) method to stringify a JavaScript object or value to a JSON string. The JSON.stringify() method serializes (converts to a JSON string) objects, arrays, and primitive values. The JSON.stringify() method takes three parameters. The first parameter is the object to be converted to JSON. The second optional parameter is a function that controls the behavior of the serialization process. The third optional parameter controls the spacing in the generated JSON string. In this JavaScript JSON Stringify example, we use the JSON.stringify() method to convert a JavaScript object to a JSON string. Click Execute to run the JavaScript JSON Stringify Example online and see the result.

How do I get a substring from a string in JavaScript?
To get a substring from a string in JavaScript, you can use the built-in string.substring(start, end) method. The first parameter specifies the index of the first character from which to get the substring (in JavaScript, indexing starts from zero). The second optional parameter specifies the index of the first character to exclude from the returned substring. If the second parameter is not specified, then the substring() method copies all characters up to the end of the string. The substring() function does not alter the original string but returns the substring from the given string. You can also get a substring from a string using the string.substr(start, length) method, which takes the number of characters to extract as its second argument. There is also a string.slice(start, end) method, which is almost identical to string.substring(), but differs in the way it handles negative argument values. In this JavaScript Substring example, we use the string.substring(start, end) method to return a substring from a string. Click Execute to run the JavaScript Substring Example online and see the result.

How do I send an AJAX request in JavaScript?
There are two ways to make AJAX calls in the browser with JavaScript: the XMLHttpRequest object and Fetch API, and several client libraries such as jQuery, Axios, and SuperAgent that use one of these two methods. The XMLHttpRequest() method is the oldest and most popular way to send AJAX requests to a server in JavaScript. The Fetch API is a new, more flexible, and easier way to make asynchronous HTTP requests to a server and is based on JavaScript Promises. To send AJAX requests to Node.js, you can use the built-in http module. In this JavaScript AJAX Request Example, we use the XMLHttpRequest() method to send asynchronous HTTP requests to the ReqBin echo URL. Click Execute to run JavaScript AJAX Request Example online and see the result.

How do I check if a string contains a substring in JavaScript?
To check if a string contains a substring in JavaScript, use the string.includes(term, start) method, which checks if the string contains the substring. The first parameter is the string to search for, and the second optional parameter specifies the position from which to search. The string.includes() method is case-sensitive. Also, you can check if the string contains a substring by using a string.indexOf(term, start), which returns the index of the substring within the string instead of the boolean value returned by the string.includes(). In this JavaScript String Contains Substring example, we use the string.includes() to check if the substring is in the string. You can see more examples of searching for substrings in strings below, including using JavaScript Regular Expressions. Click Execute to run the JavaScript String Contains Substring Example online and see the result.

How do I copy an array in JavaScript?
To copy an array in JavaScript, you can use the built-in array.slice(), array.concat(), array.from(), array.map() methods, or the spread ("...") operator. These methods create a shallow copy of the array. To deep copy an array, you can use the new built-in structuredClone() method or sequentially convert an array to JSON using JSON.stringify() and back using JSON.parse(). When cloning an array, the original array remains unchanged. In this JavaScript Copy Array example, we use the spread operator ("...") to copy an array. Below you can see more examples of copying JavaScript arrays with a detailed description of each method. Click Execute to run the JavaScript Copy Array Example online and see the result.

How do I check if an array contains an element in JavaScript?
To check if an array contains an element in JavaScript, you can use the array.includes(), array.indexOf(), array.find(), and array.filter() methods. The array.includes() method tests if the array contains the specified element and returns the boolean "true" or "false". The array.indexOf() method checks if the JavaScript array contains the specified element and returns the index of the first match or -1. You can use array.lastIndexOf() to search from the end of an array. The array.find() method allows you to check if an array contains the specified element using a custom test function. In this JavaScript Array Contains Element example, we use the array.includes() method to check if an element is in an array. Below you can see more examples of checking if an element is in an array, including a case-insensitive check. Click Execute to run the JavaScript Array Contains Example online and see the result.

How do I split a string in JavaScript?
To split a string in JavaScript, you can use the string.split(separator, limit) method. The split() method splits the given string into an array of strings using "separator" as the delimiter. The second parameter determines how many times to split the string. The string.split() method returns a new array without changing the original string. In addition to the string.split() method, you can split a string using Regular Expressions (see example below). In this Split a String in JavaScript example, we are splitting a string using the split() method. An example of splitting a string using Regular Expressions in JavaScript is shown below. Click Execute to run the JavaScript Split String Example online and see the result.

How do I parse JSON in JavaScript?
To parse JSON string in JavaScript, you can use the JSON.parse(string, function) method. The JSON.parse() method converts (or decodes) a string containing JSON data into a JavaScript object. The JSON.parse() method takes two parameters. The first parameter is the JSON string to parse, and the optional second parameter is the function used to transform the result (see the example below). If you pass an invalid JSON to the JSON.parse() method, you will get a SyntaxError exception. In this JSON Parse Example, we use the JSON.parse() method to convert a JSON into a JavaScript object. Click Execute to run the JavaScript JSON Parse Example online and see the result.

How do I convert string to array in JavaScript?
To convert a string into an array in JavaScript, you can use the string.split(separator, limit), array.from(string) methods and the spread ("...") operator. The most commonly used method is the string.split(). It converts a string into an array of strings by splitting it with a "separator". The "separator" can be a character, a string, or a regular expression. The optional "limit" parameter specifies how many times to split the string. The array.from() method and the spread ("...") operator convert a string into an array of characters. In this JavaScript String to Array conversion example, we use the string.split() method to convert a string into an array of strings. Below you can see more examples of converting strings to arrays in JavaScript, including Regular Expressions. Click Execute to run the JavaScript String to Array Example online and see the result.

How do I create a multiline string in JavaScript?
To create a multiline JavaScript string, you can enclose the string in template literals `. These multiline strings may contain newlines (\n), tab characters (\t), and other special characters. In addition to creating multiline strings, template string literals provide other useful features, such as string interpolation. Alternatively, you can build a multi-line string using the concatenation (+) operator. Template string literals make code more readable and eliminate the need for string concatenation or character escapes. In this JavaScript example, we use template string literals to create a multi-line string containing HTML tags, tabs, and line breaks. Click Execute to run the JavaScript Multiline String example online and see the result. More JavaScript multiline string examples are provided below.

How do I clear an array in JavaScript?
To clear an array in JavaScript, you can assign a new empty array "[]" to it or set the length of the array to zero (array.length = 0). The first way is the fastest, and it's handy if you don't have references to the original array anywhere else because it creates a whole new (empty) array. You must be careful with this method because the original array will remain unchanged if you refer to this array from another variable or property. The second way will clear the existing array by setting its length to 0. The length property is a read/write property of the array object, and when set to zero, all array elements are automatically removed. In this JavaScript array clearing example, we are assigning a new empty array "[]" to an existing variable. Below you can see more examples of JavaScript array clearing with a detailed description of each method. Click Execute to run the JavaScript Clear Array Example online and see the result.

How do I reverse a string in JavaScript?
JavaScript does not have a built-in method for reversing a string. To reverse a string in JavaScript, you can use a combination of three built-in methods: split(), reverse(), and join(). The first method splits a string into an array of characters and returns a new array. The second method reverses the order of elements in an array (the first element becomes last, and the element becomes first). The third method is used to concatenate all elements of an array into a new string. Another way to reverse a string in JavaScript is to use a combination of the substr() and charAt() methods. The first method returns a substring of the string, and the second method returns the specified character of the string. You can also reverse a string with a for loop, using a decrement (or increment) loop to loop through per character of the string and create a new reversed string. In this JavaScript Reverse String example, we reverse a string using the split(), reverse(), and join() methods. Click "Run" to run the JavaScript string reversal example online and see the result.

How do I reverse an array in JavaScript?
To reverse an array in JavaScript, you can use the array.reverse() method. The reverse() method allows you to reverse the order of the elements of an array so that the first element of the array becomes the last and the last element becomes the first. The reverse() method overwrites the original array. If the array is not contiguous (there are gaps between indices), then the reverse() method fills these gaps with elements with the value "undefined". You can also reverse the array manually using a for loop, but this will be slower than using the built-in array.reverse() method. In this JavaScript Array Reverse Example, we use the reverse() method to reverse an array. Below you can see more examples of reversing JavaScript arrays with a detailed description of each method. Click Execute to run the JavaScript Reverse Array Example online and see the result.

How do I concatenate strings in JavaScript?
To concatenate strings in JavaScript, you can use the "+" operator or the string.concat(str1, str2, ...) method. The "+" operator creates a new string by concatenating strings to the left and right of the operator. The string.concat() method takes one or more strings and concatenates them into a new string. The string.concat() method does not modify the provided strings but creates and returns a new string resulting from the concatenation. In this JavaScript String Concatenate example, we use the string.concat() method to concatenate strings. More examples of string concatenation are given below. Click Execute to run the JavaScript String Concatenation Example online and see the result.

How do I slice a JavaScript array?
To slice an array in JavaScript, you can use the array.slice(start, end) method, which returns a shallow copy of the original array containing the selected elements from the original array. The array.slice() method does not change the original array. The slice() method accepts two optional parameters. The first parameter specifies the starting index from which the elements will be retrieved. If the first parameter is not specified, the method assumes the default value for "start" is "0". The second parameter is the index up to which the elements should be retrieved. If the second parameter is not specified, then the array will be retrieved up to the end of the array. If the end value is greater than the length of the array, then the end value will be equal to the array's length. If the parameters "start" and "end" are negative numbers, then the elements are selected from the end of the array. In this JavaScript Slice Array Example, we use the slice() method. Click Execute to run the JavaScript Array Slice Example online and see the result.

How to Parse XML in JavaScript?
To parse XML in JavaScript, you can use DOMParser API, which converts XML strings into a structured Document Object Model (DOM). The DOM model enables easy traversal and manipulation of XML data. Additionally, you can use third-party libraries like jQuery or XML parsers, such as SAX, xml2js, and libxmljs. In this JavaScript Parse XML example, we use the parseFromString() method to parse an XML string. Below are additional examples of parsing XML in JavaScript with detailed descriptions. Click Execute to run the JavaScript Parse XML Example online and see the result.

How do I get the length of a string in JavaScript?
To get the length of a string in JavaScript, you can to use the string.length property. The length property specifies how many characters the string contains (the length of an empty string is 0). When determining the length of a string, keep in mind that spaces and various characters are also part of the string; each one is a separate character. While the length property is commonly used with other methods in JavaScript, it's important to remember that length itself is not a method and is not calculated every time (so it's fast). In this example, we get the length of a JavaScript string using the length property. Click Execute to run the JavaScript String Length Example online and see the result.

How do I insert elements into an array in JavaScript?
To insert elements into an array in JavaScript, you can use the array.push(elements), array.unshift(elements), array.splice(start, deleteCount, elements) methods, and the spread ("...") operator. The push() methods allow you to add one or more elements to the end of an array. The unshift() method allows you to add one or more elements to the beginning of an array. The push() and unshift() methods change the original array and its length. The splice() method allows you to change the contents of an array by removing or replacing existing elements or adding new elements to the array. The splice() method modifies an existing array rather than returning a new one. You can also use the spread operator ("..."), which is the modern ES6 way of inserting elements into an array. In this JavaScript Array Insert Element example, we use the push() method to insert an element into the array. Below you can see more examples of inserting elements into a JavaScript array using the push(), unshift(), and splice() methods, with a detailed description of each method. Click Execute to run the JavaScript Array Insert Element Example online and see the result.

How to trim a string using JavaScript?
To remove spaces from a string using JavaScript, you can use the string.trim() method. The trim() method removes spaces from both ends of a given string without changing the original string. The characters to be removed include space, tab, page, and line terminators (' ', \t, \r, \n, etc). The method returns a new string without any leading or trailing whitespace. To remove spaces within a string, you can use the string.replace() method. Like the string.trim() method, the string.replace() method does not change the original string but returns a copy of the string with all occurrences of the searched value replaced with the new value (see example below). In this JavaScript Trim whitespace from the string example, we remove spaces using the string.trim() method. Click Execute to run the JavaScript Trim String online and see the result

How do I find an element in JavaScript?
To find an element in Javascript, you can use the array.find(callback, thisValue) method. The find() method returns the first element in the array that matches the condition of the callback function. Otherwise, the method returns "undefined". The range of elements processed by the find() method is set before the first call to the callback. If the elements were added to the array after the find() method was called, then the callback function will not be called on such elements. The find() method does not change the array it was called on. In this JavaScript Array Find Element example, we use the find() method to search for a specific element within an array containing string elements. Click Execute to run the JavaScript Array Find Example online and see the result.

How do I clone a JavaScript array?
You can clone a JavaScript array using the Object.assign() and array.forEach() methods, a for loop, or a spread operator (the fastest way). The Object.assign() method creates a shallow array copy of all enumerable properties from one or more source objects. The spread operator ("...") is handy and fast but has been available since ECMAScript 6 and can be used to clone JavaScript arrays by expanding them. This spread operator clones multidimensional JavaScript arrays by reference, not by value. In this JavaScript Array Cloning Example, we use the spread ("...") operator to clone an array. More JavaScript array cloning examples are shown below. Click on Execute to run JavaScript Clone Array Example online and see the results.

How to Format Date in JavaScript?
In JavaScript, date manipulation is done using the Date object. To create a new Date object, you need to call the new Date() constructor. By default, almost every method on the Date object returns the date and time in the local time zone. There are various methods for converting a Date object to a string. If you want to get the date and time as a string, you can use the toLocaleDateString() method. For more verbose output, you can call the toString() method. In this JavaScript Date Format example, we display the current date and time, using the toLocaleDateString() method. Click on Execute to run JavaScript Date Format Example online and see the results.

How to check if JavaScript string starts with a string using startsWith method?
To check if a string starts with another string in JavaScript, you can use the string.startsWith(searchString, index) method. The string.startsWith() method determines if the start of this string matches the specified string or character. The first parameter specifies the search string. The second parameter is optional and specifies the index in the given string from which to search. The default value is zero. The string.startsWith() method returns a boolean value - "true" if the given string starts with the specified string, "false" otherwise. You can also determine if a string ends with a specified string by calling the string.endsWith() method. The methods are case-sensitive. In this JavaScript String startsWith example, we check if a string starts with a given string using the startWith() method with the default "index" parameter. Click Execute to run the JavaScript String startsWith Example online and see the result.

How do I merge arrays in JavaScript?
To merge arrays in JavaScript, you can use the array.concat(), array.push() methods, and the spread operator ("..."). The concat() method is used to concatenate two or more arrays into one. The concat() method does not change existing arrays but returns a new array that has the result of the merge. The push() method allows you to add one or more elements to the end of an existing array; this method changes the original array. The spread operator ("...") is a new and handy way to merge JavaScript arrays, available since ECMAScript 6. In this JavaScript Arrays Merge Example, we use the array.concat() method. Below you can see more examples of merging JavaScript arrays. Click Execute to run the JavaScript Merge Array Example online and see the result.

How do I reduce an array in JavaScript?
The JavaScript array.reduce(callback, initialValue) method is used to reduce a JavaScript array to a single value by sequentially calling the callback function on each array element and storing the intermediate result. The second optional argument is the value used for the first call to the callback function. If no "initialValue" is passed, the first element of the array will be used. The reduce() method takes the value from the callback function and passes it as an argument to the next call to the callback function. In this JavaScript Array Reduce Example, we use the reduce() method to get the sum of the array elements. Click Execute to run the JavaScript Array Reduce Example online and see the result.

How to loop through an array in JavaScript using forEach?
To loop through an array's elements, you can use the built-in array method Array.forEach(). The forEach() method takes a callback function as an argument and calls it once for each array element. The forEach() method will not be called on removed or missing array elements. However, the method will be called for elements that are in the array and have the value undefined. In this JavaScript example, we use the forEach() method to execute a given function on each element of an array. Click on Execute to run JavaScript Foreach Method Example online and see the results.