JavaScript String and String Methods

JavaScript String and String Methods

String is an object which is defined as soring and manipulating text. We can store sentences, words, and numbers in the string........

Theoretical

A string in JavaScript is an object that represents a sequence of characters. The String values in JavaScript are written with single (' ') or double quotes (" "), as long as you start and end with the same type of quote.

Scope of this article:

  • The article defines strings and ways to access the characters of strings.

  • We also discuss some useful methods of string.

  • The article does not compare the string with other data types.

Contents:-

  1. Definition

  2. How to create a String

  3. Difference between single quote and double quote.

  4. How to add two strings

  5. How to find the length of a String

  6. How to find the First and Nth characters in a string

  7. Some Important Methods Of String in JavaScript

  8. Summary

Definition

String is an object which is defined as storing and manipulating text. We can store sentences, words, and numbers in the string. You can use single or double quotes but you should choose one and stick to it. If you want to find a character from the string so you can use square brackets notation [ ] is a way to get a character at a specific index inside the square. String follows index-based access.

The index is nothing but the position of the characters of the string. The index always starts with 0. The string comes under the category of primitive data types. In JavaScript, String values are immutable, which means that they cannot be altered once created.

How to create a String

There are three ways of creating a string:

  • The string literal is created using single or double quotes. And the syntax of creating a string using string literal is given below:
// single quote
const myString = 'Hello everyone, I am Bharat.'
// double quote
const myDoubleString = "Hi, How are you? "
  • Another way is to create the String constructor.

  • new String(): When String is called a constructor (with new), it creates a String object, which is not primitive.

const a = new String("Hello world ");

16.png

  • Template Literals:-

Template literals are an ES6 feature. The Template literals have solved some problems with single or double quotes. The Template literals use back-ticks (`` ) for storing the content. In Template literal, we can use multiline strings, variables and expressions into strings. Also, we can use single and double quotes inside it. Template literals It is a very big topic, and it was necessary to cover only something, so I did, but I would like you to read this article.

Syntax:

// From MDN syntax
`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tagFunction`string text ${expression} string text`

Examples:

// single line string and single quote
const name = `I'm Bharat.`;

// multiline string and variable substitution
const wlcUser = `Hello
                ${name}!
                Welcome to The Grand Woodward Hotel.`;

Difference between single quote and double quote.

  1. The main work of both quotes is that they form a string and are used to represent it as.
var myFriend = 'Vani ';

var myFriend = "Vani";
myFriend = myFriend [true]
  1. Whichever quoting style you open a string with, close it with the same style.

  2. The reason why you might want to use one type of quote over the other is if you want to use both in a string. This might happen if you want to save a conversation in a string and have the conversation in quotes.

  3. The second use of it would be saving a div tag with various attributes in quotes, all within a string. A wise selection of quoting can help you from escaping single (') or double(") quotes within a string. Read more about this 'Single' vs "Double".

var outputBox = '<div id="output"></div>' ;

How to add two Strings?

There are three ways to add two String, to begin with

Concatenating string with plus + operator

In JavaScript, when + the operator is used with a String value, it is called a Concatenation operator. You can update or build a new string out of other strings by concatenating them together.

"Hello, I am Bharat." + " From India"

Note take care of white space " " and concatenation does not add space between concatenated strings.

Concatenating strings with the plus equals operator +=

In JavaScript, we can also use += operator to concatenate a string onto the end of an existing string variable. This can be very useful to break and update short strings and long strings over several lines. For example

var name = "Bharat";

name += " chotwani";

name += " is a good human";

similarly, we can use this method to update or build or add two variables.

var lastName = " Sharma";

name + lastName ;

How to find the length of a String?

You can find the length of a String value by writing .length after the string variable or string literal.

var bestFriendName = "Saumya Sharma";

console.log(bestFriendName.length);

The value 13 would be displayed in the console. Note that the space character between "Saumya" and "Sharma" is also counted. For example, if we created a variable const firstName = "Arav" , we could find out how long the string Arav is by using the first <code>name.length</code> property.

How to find the First and Nth characters in String?

The first character in String:

  • Bracket notation is a way to get a character at a specific index within a string. You can find the First character by Index access.
const myName = "Bharat."
const indexValue = myName[0];
console.log(indexValue);

hashnode.png

In the above example, B is at index 0, h is at index 1, and so on.

Nth character in String:

You can also use bracket notation to get the character at other positions within a string.

Remember that the index starts counting at 0, so the first character is the zeroth character. Also, you can use charAt method to find nth characters in the String.

const myName = "Bharat."
const thirdIndexValueOfString = myName[2];
console.log(thirdIndexValueOfString);

hashnode2.png

Some Important Methods Of String in JavaScript

charAt(): charAt() a feature introduced in ES1. In charAt() we give index access value as a parameter and charAt() gives us the character of the string.

Syntax:

string.charAt(index)

Examples:

const text = "Welcome home";

console.log(text.charAt(0));    // W
console.log(text.charAt(1));     // e
console.log(text.charAt(2));    // l
console.log(text.charAt(7));   // ' '

charCodeAt(): charCodeAt() the feature is also introduced in ES1. The charCodeAt() method returns the Unicode of the character at a specified index (position) in a string. The charCodeAt() is also taking the index value as a parameter and gives us a Unicode of the character.

Syntax:

string.charCodeAt(index)

Examples:

const text = "Welcome home";

console.log(text.charCodeAt(0));   // 119
console.log(text.charCodeAt(1));   // 101
console.log(text.charCodeAt(7));  // 32
  • concat(): Concat means concatenating, it is adding a new string to the current string. The concat() method joins two or more strings. The concat() the method does not change the existing strings. The concat() the method returns a new string.

Syntax:

string.concat(string1, string2, ..., stringX)

Examples:

const text = "Welcome home";
const userName = " Arav";
const wlcUser = text.concat(userName);

console.log(wlcUser);   // 'welcome home Arav'
  • startsWith(): feature is introduced in ES6. This method returns a true or false value and the point is the startsWith() the method returns the true value to us when we pass the substring as a parameter to this method and If we pass some different value in this method, which does not match inside the main string, then it will give us a false value.

Syntax:

string.startsWith(searchValue, start)

Examples:

const text = "Welcome home";

console.log(text.startsWith("Welcome"));   //true
console.log(text.startsWith("home"));   //false because this string is not start with home
console.log(text.startsWith("home", 7));  //false
console.log(text.startsWith("home", 8)); //true

The second example shows that it takes two values ​​first <code>searchValue</code> or second start. In the search value, we can put the sub-string and in the start, we can put the position in which the substring starts. for example, the home start value [index value] is 8 that's why the method returns true.

  • endsWith(): feature is also introduced in ES6. This method returns a true or false value and the point is the endsWith() the method returns the true value to us when we pass the substring as a parameter to this method and If we pass some different value in this method, which does not match inside the main string, then it will give us a false value.

Syntax:

string.endsWith(searchvalue, length)

Examples:

const text = "Welcome home";

console.log(text.endsWith("Welcome"));   //false because this string is end with home
console.log(text.startsWith("home"));   //true
  • slice(): slice In vanilla English slice means a cut from a larger portion. The slice() method extracts a part of a string.

The slice() the method returns the extracted part in a new string. The slice() the method does not change the original string. The start and end parameters specify the part of the string to extract. The first position is 0, the second is 1... A negative number selects from the end of the string. slice() the feature is introduced in ES1.

Syntax:

string.slice(start, end)

Examples:

const text = "Welcome home";

console.log(text.slice(0,  6)); // 'welcome'
console.log(text.slice(-4));   // 'home'
  • search(): The search() method matches a string against a regular expression The search() method returns the index value/position of a sub-string in a string by finding it. In the search method, when the substring is not found/matched, it returns -1. Also, the search method is case-sensitive. And search() the feature is introduced in ES1.

Syntax:

string.search(searchValue)

Examples:

const quotes = "The purpose of our lives is to be happy.";

console.log(quotes.search("The"));   // 0
console.log(quotes.search("of"));     // 12

console.log(quotes.search(/of/));    // 12 and '/ /' is regular expression
console.log(quotes.search(/to/i));  // 28 adn here 'i' is for case-insensitive.
  • split(): Split means break or cause to break into parts.

Now the split() method break the main string into an array of substrings.

split-method.png

The split() method returns the new array and it is not change the main string. In the above example, we can see that we are using (" ") as a separator, We can also use an integer value.

Syntax:

string.split(separator, limit)

Examples:

const quotes = "The purpose of our lives is to be happy. "; console.log(quotes.split(" ")); 

// (9) ['The', 'purpose', 'of', 'our', 'lives', 'is', 'to', 'be', 'happy.']... const myArray = quotes.split(" ", 8); console.log(myArray); 
// (8) ['The', 'purpose', 'of', 'our', 'lives', 'is', 'to', 'be']
  • substr(): substr() method extracts a part of the main string and takes index as argument. The substr() method begins at a specified position(index value), and returns a extract part. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

Syntax:

string.substr(start, length)

Examples

const quotes = "The purpose of our lives is to be happy. "; 

console.log(quotes.substr(1, 8)); // 'he purpo' 

console.log(quotes.substr(12)); // 'of our lives is to be happy.'

Summary

  1. String is a data type in programming languages and manipulating text.
  2. There are three ways of creating string.
    • Using single and double quotes
    • By new key work
    • Template string
  3. Concating string means we can add two strings with plus operator + .
  4. We can find length of a string by using .length .