JavaScript String

Introduce with JavaScript Strings

Overview

String is represent human readable sequence of characters. String is a combination of characters. It will be a word and a sentence.

In JavaScript some common method are use with string. For Example to identify the length of a string we use str.length (suppose str is a string variable), concatenate 2 string useing “+” operator like (str1 + str2) or using templet String like ({`${str1} ${str2}`}) or str1.concat(str2), extracting substrings with the substring() method, define substring location using indexOf().

some of common methods of strings are charAt(), concat(), replace(), indexOf(), lastIndexOf(), slice(), split(), substr(), startWith(), trim() etc.

Let’s talk about a little bit about these method.

charAt()

This method return the character of specific index number. This method take a parameter. Index number and return the character of given index number.

example:

const str = “Tanvin”

str.charAt(1) // output “a”

concat()

To add 2 string we use contact() method.

exmaple:

“Tanvin”.concat(“ Ahmed”)// output “Tanvin Ahmed”

replace()

This method use to replace string position.

example:

(“Tanvin, Ahmed”).replace(“Ahmed”, “Touhid”) // output : “Tanvin Touhid”

indexOf()

This method is use to identify the position of substring of a string. This method return index number of a string.

example:

const str = “Tanvin Ahmed”;

console.log(indexOf(Ahmed)) // output : 7

lastIndexOf()

The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value. If search string is not found it return -1.

example:

const str = “Tanvin Ahmed”;

console.log(indexOf(Ahmed)) // output : 7

slice()

slice method method use to cut a string from specific position to another specific position. In this method we give 2 parameter, 1st one where is the start position and 2nd one is after the last position. It means if you wnat to strop slicing at position 5, then you give the second value 6. It return a new string.

example:

const str = “Tanvin Ahmed”;

console.log(str.slice(0, 7)) // output : “Tanvin”

split()

Split() method convert a string into an array. This method need a parameter that is define that you will spice depending on what. If you git (“”) it return you a character array.

example:

const str = “Tanvin Ahmed”;

console.log(str.split(“ ”)) // output: [“Tanvin”, “Ahmed”]; (cause white space)

trim()

It remove extra space from a string.

example:

const str = “Tanvin Ahmed ”;

console.log(str.trim()) // output: “Tanvin Ahmed” [It remove last white space].

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store