Javascript String Variable Types – POFTUT

Javascript String Variable Types

While developing Javascript applications we generally need some type that can hold text and string data. We call this type of variable as a string. The string can hold names, street info, paragraph, explanation, etc. The string is the type used for text data. String variables can be defined in various ways.

  • These are string variables

  • val is a String object the very similar to a string variable

There are methods to use with the string data type. The string data type is wrapped as a String object in Javascript to provide this method.

Get The Length of String

To get the length of the string is easy as below. Length is equal to the number of characters including spaces.

Code:

  • length provides the length of string

Output:

  • As we see the second line of output is 7 where the second string has space at the end

Find Index of String

If we are looking at a characters position in the string we can use indexOf function

Code:

Output:

  • If the char is not existed in the string -1 is returned.

Combine Strings

As we know strings cannot be changed after initialized so to add some string concat  can be used

LEARN MORE  Linux tr Command Tutorial With Examples

Code:

Output:

Return A Char With Index

To get a character from the specified index  charAt function is used. Index numbers start from 0.

Code:

Output:

Replace String

To replace the string replace method is used. There are two parameters.

Code:

  • me” is the string we want to replace
  • “you” the new string

Output:

Search String

Searching for a specified string in a string. Returns the index of the search term.

Code:

Output:

Substring

There are two types of substring method. Substring is used to extract some part of a string by providing index values.

Code:

  • starts index for a substring
  • ends index for a substring

Output:

Code:

  • starts index for a substring
  • is the length of the substring from start index which means we will get 2 characters
LEARN MORE  Python Regular Expression Operations - Regex

Output:

To Lower Case

All uppercase characters can be converted into lowercase characters with toLowerCase method

Code:

Output:

To Upper Case

All lowercase characters can be converted into uppercase characters with toUpperCase method

Code:

Output:

Convert To String

We may need numeric or other data types to convert string to manipulate them.

Returned object type will be a string

Code:

Output:

Leave a Reply

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