Hello, everyone, welcome back, in this module, I am going to discuss string and methods in JavaScript. In the previous module, we learned to break and continue statements in JavaScript. So, let’s start.
String and Methods in JavaScript
In JavaScript, a string is a sequence or group of characters written inside either single or double quotes. It is used to store data or values in the form of text and perform operations on it.
Example
// string inside double quotes. let name="My name is Rohit."; console.log (name); // string inside single quotes. const city='I live in India.'; console.log(city); //Output //My name is Rohit. //I live in India.
Unlike other programming languages, in JavaScript, we can also create a string using a backtick character (`), which is just to the left of key 1 in the keyboard.
var message=`Hello, World!`; console.log(message); //Output //Hello, World!
How to create a string in JavaScript?
In JavaScript, we can create a string in 2 ways:
Primitive or string literal in JavaScript
We can create strings using primitive or string literal by enclosing the string value inside single or double quotes.
Syntax
let variable_name="string value" var variable_name='string value'
Here, we can create a variable using var, let, and const keywords in JavaScript.
let a="Hello"; console.log(typeof(a)); //Output //string
String object in JavaScript
When a string is created using a new keyword, it is known as a string object.
Syntax
var variable_name=new String(“string value”);
Example
var str=new String("Hello, World"); console.log(typeof(str)); //Output //Object
How to access the characters of a string in JavaScript?
We can easily access the characters of a string using its index number. The index number starts from 0 and ends at (length of string-1) in the string.
const a="JavaScript" console.log(a[2]); // v
String with an escape character
Suppose you want to print the message, This is a “JavaScript” tutorial.
If you print this message in JavaScript like this as shown below, then you will get a syntax error:
console.log("This is a "JavaScript" tutorial.");
So, to print the above message, we can enclose the string inside a single quote.
console.log('This is a "JavaScript" tutorial.');
Another way to print the above message is to use backslash escape characters \.
console.log("This is a \"JavaScript\" tutorial.");
Similarly, we can print the message, This is a ‘JavaScript’ tutorial, using either backslash escape characters or enclosing the string inside double-quotes.
console.log("This is a 'JavaScript' tutorial."); console.log('This is a \'JavaScript\' tutorial.');
String methods in JavaScript
- charAt() in JavaScript
It is used to return the character in the string at the given index.
Syntax
string.charAt(index)
Exampleconst a="String in JavaScript." console.log(a.charAt(5)); //Output //g
- charCodeAt() in JavaScript
It is used to return the Unicode of the character at the given index in a string.
Syntax
string.charCodeAt(index)
Example
const s="JavaScript" console.log(s.charCodeAt(1)); //Output //97
Here, in the above example, the character at index 1 is ‘a’, so its Unicode is 97.
We can use the length property along with the charCodeAt() method to find the Unicode of the last character in a string.Example
const a="JavaScript"; let len=a.length; console.log(a.charCodeAt(len-1)); //Output //116
- replace() in JavaScript
This method is used to replace a part of a given string or the whole string with a new string.
Syntax
string.replace(original_string,new_string)
original_string is a string to be replaced.
new_string is a string used to replace the original string.
Exampleconst a="JavaScript"; console.log(a.replace("Java","Type")); console.log(a.replace("JavaScript","CoffeeScript")); //Output //TypeScript //CoffeeScript
We can also use regular expressions in place of the original string to be replaced with a new string.
Example
const a="JavaScript is a Programming Language."; console.log(a.replace("a","A")); console.log(a.replace(/a/g,"A")); //Output //JAvaScript is a Programming Language. //JAvAScript is A ProgrAmming LAnguAge.
Here, in the above example, when we are not using a regular expression, only the first occurrence of ‘a’ is replaced with ‘A’ but with the use of a regular expression, all the character ‘a’ gets replaced with ‘A’. In the given regular expression /a/g, g means that the character ‘a’ is searched globally in a given string and gets replaced with ‘A’.
- concat() in JavaScript
It is used to join or concatenate two or more strings.
Syntax
string.concat(string1,string2)
Exampleconst s1='String'; const s2='in'; const s3='JavaScript' console.log(s3.concat(s1)); console.log(s1.concat(s2,s3)); console.log(s1.concat(' ',s2,' ',s3)); //Output //JavaScriptString //StringinJavaScript //String in JavaScript
- fromCharCode() in JavaScript
This method is used to return the ASCII character of a given Unicode. It uses a String object instead of a given string to invoke itself.
Syntax
String.fromCharCode(Unicode)
Exampleconsole.log(String.fromCharCode(97)); console.log(String.fromCharCode(78)); //Output //a //N
- trim() in JavaScript
It is used to remove white spaces from both ends of a given string.
Syntax
string.trim()
Examplevar str = " Trim method in JS. "; console.log(str.trim()); //Output //Trim method in JS.
- startsWith() in JavaScript
It is a method used to return true if the given string starts with the specified character or string, otherwise, it returns false.
Syntax
string.startsWith(string)
Exampleconst str='Programming language'; console.log(str.startsWith('P')); console.log(str.startsWith('program')); //Output //true //false
startsWith() is a case sensitive method, which means that uppercase and lowercase letters are treated differently.
Example
const str='Programming language'; console.log(str.startsWith('Program')); console.log(str.startsWith('program')); //Output //true //false
We can also provide a start position up to which the given character or string to be searched within a string.
Syntax
string.endsWith(string,startposition)
startposition is an index number.Example
const str='JavaScript'; console.log(str.startsWith('Java',0)); console.log(str.startsWith('Java',3)); console.log(str.startsWith('Script',4)); //Output //true //false //true
- endsWith() in JavaScript
This method is used to return true if the given string starts with the specified character or string, otherwise, it returns false.
Syntax
string.endsWith(string)
Exampleconst str='Programming language'; console.log(str.endsWith('age')); console.log(str.endsWith('g')); //Output //true //false
We can also provide an end position up to which the given character or string to be searched within a string.
Syntax
string.endsWith(string,endposition)
endposition is an index number.As I have mentioned earlier, the index of a string starts from 0, so the string is searched from 0 to endposition -1.
Example
const str='JavaScript'; console.log(str.endsWith('Java',4)); console.log(str.endsWith('Java',3)); console.log(str.endsWith('Script',10)); //Output //true //false //true
endsWith() is a case sensitive method, which means that uppercase and lowercase letters are treated differently.
Example
const str='Programming language'; console.log(str.endsWith('age')); console.log(str.endsWith('Age')); //Output //true //false
- toString() in JavaScript
It is used to convert a numeric or boolean value to a string.
Syntax
string.toString(number)
string.toString(boolean)
Examplelet num=5; console.log(typeof num); num=num.toString(); console.log(typeof num); let bool=true; console.log(typeof bool); bool=bool.toString(); console.log(typeof bool); //Output //number //string //boolean //string
- toUpperCase() in JavaScript
It is used to convert the given string into uppercase.
Syntax
string.toUpperCase()
Examplelet name='Rahul Sharma'; console.log(name.toUpperCase()); //Output //RAHUL SHARMA
- toLowerCase() in JavaScript
It is used to convert the given string into lowercase.
Syntax
string.toLowerCase()
Examplelet name='RAHUL SHARMA'; console.log(name.toLowerCase()); //Output //rahul sharma
- repeat() in JavaScript
This method is used to print the given string ‘n’ number of times.
Syntax
string.repeat(n)
where n is the number of times a string or character is printed.
Examplelet s='Hii'; console.log(s.repeat(5)); //Output //HiiHiiHiiHiiHii
- search() in JavaScript
It is used to find a string within a given string and return the starting index number of the string to be searched for if found otherwise, it returns -1.
Syntax
string.search(search_string)
search_string is the string to be searched in a given string.
Examplevar str='This is a JavaScript tutorial.'; console.log(str.search('JavaScript')); //Output //10
var a='This is a JavaScript tutorial.'; console.log(a.search('The')); //Output //-1
search() is a case-sensitive method.
Example
var str='This is a JavaScript tutorial.'; console.log(str.search('JavaScript')); console.log(str.search('javascript')); //Output //10 //-1
- includes() in JavaScript
If the given string or character is found within a string, it returns true otherwise it returns false. It is a case-sensitive method.
Syntax
string.includes(search_string)
Examplevar str='This is a JavaScript tutorial.'; console.log(str.includes('Java')); console.log(str.includes('the')); //Output //true //false
There are many more string methods in JavaScript. The list of other string methods is listed below:
- indexof()
- lastIndexOf()
- split()
- slice()
- substr()
- substring()
I hope this module (String and methods in JavaScript) has helped you a lot to know about strings and their methods in JavaScript. Try all the methods by yourself to gain a better understanding of the string. For more modules, stay connected with us. Keep coding!