Split method in JavaScript

Split method in JavaScript?

Ans- The split method in JavaScript is used to split a string into an array of substring based on a specified separator and returns the new array.

Syntax:

JavaScript
string.split(separator, limit)

Parameters:

  • Separator: This parameter specifies the character or regular expression used to specify where to split the string. It can be a string or a regular expression. If omitted, the entire string will be a single element in the resulting array.
  • limit: optional. An integer that specifies that maximum number of splits. The array will have most limit+1 element. If omitted, the entire string will be split.

Example:

JavaScript
var sentence = "This is my simple sentences";
var words = sentence.split(" ");
console.log(words); // [ 'This', 'is', 'my', 'simple', 'sentences' ]

Example 2

JavaScript
var sentence = "This is a sample sentence with a lot of words";
var words = sentence.split(" ", 4);
console.log(words); //[ 'This', 'is', 'a', 'sample' ]

In this example, the split(” “, 4) method splits the sentence string into an array of substrings using space as the delimiter. However, it specifies a limit of 4, which means it will create an array with at most 4 + 1 = 5 elements.

The resulting words array will contain the first four words from the sentence: [“This”, “is”, “a”, “sample”]. Since the limit was set to 4, the splitting stops after reaching the limit, and the rest of the sentence is not included in the array.

0%
1 votes, 5 avg
39

Start Your Coding Journey!!

Thanks for Participating!!!


Created on By PC Prajapat

JavaScript Interview Questions Quiz Part 3

Register 

1 / 10

Which of the following operators has the lowest precedence?

2 / 10

What will the following code output?

let x = 5;
let y = Object.freeze({x});
y.x = 10;
console.log(y.x);

3 / 10

What is the output of the following code?

(function(){
var a = b = 3;
})();
console.log(typeof b);

4 / 10

What is the result of null == undefined in JavaScript?

5 / 10

Which of the following correctly clones an object in JavaScript?

6 / 10

How does the ‘this’ keyword behave inside an arrow function in JavaScript?

7 / 10

How does the ‘this’ keyword behave inside an arrow function in JavaScript?

8 / 10

Which of the following methods will stop further event propagation in JavaScript?

9 / 10

What will be the output of the following code?

function test() {
var a = b = 5;
}
test();
console.log(typeof b);

10 / 10

Which of the following is not a primitive data type in JavaScript?

Your score is

The average score is 41%

Share with your friends.

LinkedIn Facebook
0%

Exit

Rate us.

Thanks for your valuable feedback.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *