10 JavaScript String Methods, You Should Must Know

10 JavaScript String Methods, You Should Must Know

In this article, I will be explaining about string primitive data type in JavaScript and its few features which is helpful for developers.

What is String in JavaScript

The String object is used to represent and manipulate a sequence of characters. Strings are useful for holding data that can be represented in text form.

Creating String

Strings can be created as primitives, from string literals, or as objects, using the String() constructor:

const string1 = "A string primitive";
const string2 = 'Also a string primitive';
const string3 = `Yet another string primitive`;
const string4 = new String("A String object");

String primitives and string objects can be used interchangeably in most situations String literals can be specified using single or double quotes, which are treated identically, or using the backtick character `.

Let’s discuss below string method one by one by example and usage

1. charAt()

2. slice()

3. split()

4. replace()

5. repeat()

6. includes()

8. match()

9. valueOf()

10. substr()


1. charAt()

charAt() method returns a string representing a character at a specific position in a string. The position must be between 0 and string. length-1. If the position is out of bounds, the charAt() method will return an empty string.

In JavaScript, the syntax for the charAt() method is: string.charAt([position]);

For example:

var my_string = 'Dhiraj Kumar';

console.log(my_string.charAt(0)); - return T
console.log(my_string.charAt(1)); - return h
console.log(my_string.charAt(2)); - return i
console.log(my_string.charAt(3)); - return r

2. slice()

slice() method extracts parts of a string and returns the extracted parts in a new string.

Use the start and end parameters to specify the part of the string you want to extract.

The first character has the position 0, the second has position 1, and so on.

Use a negative number to select from the end of the string.

Syntax

slice(beginIndex)
slice(beginIndex, endIndex)

Let's take some example

let str1 = ‘my name is dhiraj kumar', // the length of str1 is 24.
    str2 = str1.slice(0, 8),
    str3 = str1.slice(4, -2),
    str4 = str1.slice(0),
    str5 = str1.slice(-1);
console.log(str2)  // OUTPUT: my name 
console.log(str3)  // OUTPUT: ame is dhiraj kum
console.log(str4)  // OUTPUT: m
console.log(str5)  // OUTPUT: r

3. split()

The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.

Syntax

split()
split(separator)
split(separator, limit)

separator Optional The pattern describing where each split should occur. The separator can be a simple string or it can be a regular expression

limit Optional A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

Example

Var  mystr = ‘My name is Dhiraj Kumar';
const words = mystr.split(' ');
console.log(words[3]);  // expected output: "Dhiraj"

const chars = mystr.split('');
console.log(chars[8]);  // expected output: "s"

const strCopy = mystr.split();
console.log(strCopy);  // expected output: Array ["My name is Dhiraj Kumar "]

4. replace()

replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

Note: If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier .

The original string is left unchanged.

Example

const p = ‘my name is dhiraj kumar  .my city is pune';

console.log(p.replace('my', 'your'));
// expected output: " your name is dhiraj kumar .your city is pune"

const regex = i/my/;
console.log(p.replace(regex, 'your'));
// expected output: " my name is dhiraj kumar  .your city is pune "

5. repeat()

The repeat() method returns a new string with a specified number of copies of the string it was called on. Examples

'abc'.repeat(-1)    // RangeError
'abc'.repeat(0)     // ''
'abc'.repeat(1)     // 'abc'
'abc'.repeat(2)     // 'abcabc'
'abc'.repeat(3.5)   // 'abcabcabc' (count will be converted to integer)
'abc'.repeat(1/0)   // RangeError

6. includes()

The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate.

Syntax

includes(searchString)
includes(searchString, position)

Parameters

searchString A string to be searched for within str.

position Optional The position within the string at which to begin searching for searchString. (Defaults to 0.)

Return value true if the search string is found anywhere within the given string; otherwise, false if not.

Example

'Dhiraj Kumar'.includes('kumar')  // returns false
'Dhiraj Kumar'.includes('Kumar')  // returns true

The search() method searches a string for a specified value, and returns the position of the match.

The search value can be string or a regular expression.

The search() method returns -1 if no match is found.

Example - Perform a case-sensitive search:

let str = "My name is Dhiraj kumar";
str.search("Dhiraj")   // Returns 10

Example - Perform a case-insensitive search:

let str = " My name is Dhiraj kumar ";
str.search(/dhiraj/i)   // Returns 10

8. match()

The match() method retrieves the result of matching a string against a regular expression.

Example - Perform a global, case-insensitive search for "ain":

let str = "The main reason behind pain is gain";
str.match(/ain/gi)   // Returns ain,ain,ain

9. valueOf()

The valueOf() method returns the primitive value of a String object.

Examples

var x = new String('Hello world');
console.log(x.valueOf()); // Displays 'Hello world'

10. substr()

The substring() method extracts characters, between to indices (positions), from a string, and returns the substring.

The substring() method extracts characters between "start" and "end", not including "end".

If "start" is greater than "end", substring() will swap the two arguments, meaning (1, 4) equals (4, 1).

If "start" or "end" is less than 0, they are treated as 0.

The substring() method does not change the original string.

const str = 'Dhiraj';

console.log(str.substring(1, 3));
// expected output: "hir"

console.log(str.substring(2));
// expected output: "iraj"

That's all for this Blog developers and with that, it's a wrap! I hope you found the article useful.

I create content about Programming, and Productivity, If this is something that interests you, please share the article with your friends and connections.

Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

I would strongly recommend you to Check out my YouTube Channel youtube.com/c/codeasitis where i post programming video and don't forget to subscribe to my Channel. I would love to connect with you at Twitter ( twitter.com/codeasitis1 ) | Instagram ( instagram.com/codeasitis )

See you in my next Blog article, Take care!!