In JavaScript, you can use the split()
method to split a string into an array of substrings. The split()
method takes one argument, which is the delimiter that separates the substrings.
For example, to split a string of words separated by spaces:
var sentence = "The quick brown fox";
var words = sentence.split(" ");
console.log(words); // ["The", "quick", "brown", "fox"]
You can also split a string using a specific character, such as a comma:
var list = "apple,banana,cherry";
var items = list.split(",");
console.log(items); // ["apple", "banana", "cherry"]
You can also split a string into an array of substrings of a given length. You can use the .match()
method with the .replace()
method to achieve this.
var str = "Thequickbrownfox";
var chunks = str.match(/.{1,3}/g);
console.log(chunks); // ["The", "qui", "c", "kb", "row", "nfo", "x"]
It’s worth mentioning that the split()
method will not change the original string, it will return a new array of substrings.
You can use any of the above methods to split a string in JavaScript, depending on your specific requirements.
Also Read:
- What Is AJAX?
- List of JavaScript Functions
- How To Copy An Array In JavaScript
- How To Get All Unique Values In A JavaScript Array
- Convert int to string in JavaScript
- How To Check If An Object Is An Array In JavaScript
- How To Randomize An Array In JavaScript
- How To Replace All Occurrences Of A Character In A String?
- How To Split A String In JavaScript?
- How To Replace Multiple Spaces With Single Space In JavaScript
- How To Replace All Character In A String In JavaScript
- How To Check If A String Contains A Substring In JavaScript
- How To Loop Through An Array In JavaScript
- How To Check If A Value Exists In An Array In JavaScript
- How To Remove Duplicates From An Array Using JavaScript
- How To Create Multiline Strings In JavaScript
- How To Remove A Specific Element From An Array In JavaScript
- How To Define A Function In JavaScript?
- How To Concatenate Two String Arrays In JavaScript
- How To Get Image Size (Height & Width) Using JavaScript
- How To Change Image Size In JavaScript
- How To Increase and Decrease Image Size Using JavaScript
- How To Trigger Or Pause A CSS Animation In JavaScript
- How To Check If A Variable Is Undefined Or Null In JavaScript
- How To Check If A Variable Exists Or Is Defined In JavaScript
- How To Change The Background Color With JavaScript
- How To Encode A URL With JavaScript
- How To Decode A URL In JavaScript