Skip to content

Split and join in JavaScript | Examples and Use in Array/Strings

  • by

Split and Join method can use to a string with an array or useful for static find-and-replace.

As per name indicates split() function breaks up a string at the specified separator and the joint() function is joined by the string separator. 

Read this tutorial:-

JS Find and Replace string with Split/Join

Let’s write a program to find and replace in JavaScript with static search and replace strings.


Note:- always faster to use String.split() and String.join() than to use String.replace(). Compare:

<!DOCTYPE html>

    	var myString = '......some long text.....'; 
		var n = myString.split(".").join(" "); // Replace the dot with space




Split and join in JavaScript

Read another way:- JavaScript replace all Word | space, comma | special characters

Using split/join to replace a string with an array

var item = 'Hello, 1, my name is 2.';
var arr = new Array();
arr [1] = 'admin';
arr [2] = 'guest';
for (var x in arr)
    item = item.replace(x, arr[x]);

Q: Is str.split(someString) .join(someOtherString) equivalent to a replace?

Answer: No, they are not equivalent.

replace() allows you to replace the matched text with some other string.

split() method just creates an array from an input string and a delimiter string

The join() method returns a string containing the values of all the elements in the array glued together using the string parameter passed to join()

You can use split() and join() to emulate replace() method, but It will make your code less clear to understand.

var a = 'Dont use join and split when replace is preferable';

a.split(' ').join('') === a.replace(/\s+/g, ''); // will return true :)

Do comment if you have any questions and doubts on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading