TypeScript String
A string in TypeScript is a primitive data type that’s used to store text data. A TypeScript string operates with a sequence of characters.
String values are enclosed in either single (‘) or double quotes (“). An array of characters functions similarly to a string.
Here’s the syntax:
let var_name = new String(string);
The following are three ways in which we can create a string.
Single quoted strings
The single-quoted strings are strings that are enclosed within single quotes (‘). Any text between the quotes is considered a string.
let SamplesingleQuotedString = 'Hi, Welcome to Itsourcecode!';
console.log(SamplesingleQuotedString);
Output:
Hi, Welcome to Itsourcecode!
Double quoted strings
The double-quoted strings are strings that are enclosed within double quotes (“). Any text between the quotes is considered a string.
let SampledoubleQuotedString = "Hi, Welcome to Itsourcecode!";
console.log(SampledoubleQuotedString);
Output:
Hi, Welcome to Itsourcecode!
Back-ticks strings
The Back-ticks strings are strings that are enclosed within back-ticks (`). They are also known as template literals and can span multiple lines and embed expressions.
let website = "Itsourcecode";
let backticksString = `Hi welcome to, ${website}!`;
console.log(backticksString);
Output:
Hi welcome to, Itsourcecode!
TypeScript String Format
You can format strings in TypeScript in several ways:
Concatenation (+)
You can merge strings using the + operator.
let website: string = 'Itsourcecode';
let msg: string = 'Hi welcome to ' + website + '!';
console.log(msg);
Output:
Hi welcome to Itsourcecode!
Template Literals
Enclosed by back-tick (`), template literals can contain placeholders (${expression}).
let website: string = 'Itsourcecode';
let msg: string = `Hello welcome to ${website}!`;
console.log(msg);
Output:
Hello welcome to Itsourcecode!
Using eval() function
The eval() function can be used to perform string interpolation within a regular string.
let website: string = 'Itsourcecode';
let msg: string = `Hi, Welcome to ${website}!`;
console.log(eval("`" + msg + "`"));
Output:
Hi, Welcome to Itsourcecode!
Multi-Line String
The Multi-Line String are strings that span multiple lines. In TypeScript, you can create multi-line strings using back-ticks.
let multiLineString = "Hi, Welcome to Itsourcecode!";
console.log(multiLineString);
Output:
Hi, Welcome to Itsourcecode!
String Literal Type
In TypeScript, you can use string literal types to allow an exact value that a string must have.
type Greetings = "Hi, Welcome to Itsourecode!";
let greeting: Greetings = "Hi, Welcome to Itsourecode!";
console.log(greeting);
Output:
Hi, Welcome to Itsourecode!
TypeScript String Methods
Here are some of the commonly used TypeScript string methods:
1. charAt()
The charAt() method fetches the character at a specific index.
let samplestring = "Hi, Welcome to Itsourcecode!";
console.log(samplestring.charAt(4));
Output:
W
2. concat()
The concat() method combines two or more strings.
let Samplestring1 = "Welcome to";
let Samplestring2 = ", Itsourcecode!";
console.log(Samplestring1.concat(Samplestring2));
Output:
Hi, Welcome to Itsourcecode!
3. indexOf()
The indexOf() method finds the position of the first occurrence of a substring.
let Samplestring = "Hi, Welcome to Itsourcecode!";
console.log(Samplestring.indexOf("Itsourcecode"));
Output:
15
4. replace()
The replace() method substitutes a specified substring with another substring.
let Samplestring = "Hi, welcome to Universe!";
console.log(Samplestring.replace("Universe", "Itsourcecode"));
Output:
Hi, welcome to Itsourcecode!
5. split()
The split() method divides a string into an array of substrings.
let Samplestring = "Hi, welcome to Itsourcecode!";
console.log(Samplestring.split(","));
Output:
[ 'Hi', ' welcome to Itsourcecode!' ]
6. toUpperCase()
The toUpperCase() method changes all string characters to uppercase.
let Samplestring = "Hi, welcome to Itsourcecode!";
console.log(Samplestring.toUpperCase());
Output:
HI, WELCOME TO ITSOURCECODE!
7. toLowerCase()
The toLowerCase() method changes all string characters to lowercase.
let Samplestring = "Hi, welcome to Itsourcecode!";
console.log(Samplestring.toLowerCase());
Output:
hi, welcome to itsourcecode!
8. charCodeAt()
The charCodeAt() method returns the Unicode of the character at a specified index.
let Samplestring = "Hi, welcome to Itsourcecode!";
console.log(Samplestring.charCodeAt(1));
Output:
105
9. includes()
The includes() method checks whether a string contains a specified string.
let Samplestring = "Hi, welcome to Itsourcecode!";
console.log(Samplestring.includes("Itsourcecode"));
Output:
true
10. endsWith()
The endsWith() method checks whether a string ends with a specified string.
let Samplestring = "Hi, welcome to Itsourcecode!";
console.log(Samplestring.endsWith("!"));
Output:
true
11. startsWith()
The startsWith() method checks whether a string starts with a specified string.
let Samplestring = "Hi, welcome to Itsourcecode!";
console.log(Samplestring.startsWith("HI"));
Output:
true
12. lastIndexOf()
The lastIndexOf() method gives the position of the last occurrence of a specified value in a string.
let Samplestring = "Hi, welcome to Itsourcecode!";
console.log(Samplestring.lastIndexOf("to"));
Output:
12
13. localeCompare()
The localeCompare() method compares two strings and returns a number that tells whether the reference string is greater than, equal to, or less than the compare string.
let Samplestring = "Itsourcecode";
let result = Samplestring.localeCompare("Itsourcecode");
console.log(result);
Output:
0
14. match()
The match() method finds the matches of a regular expression in a string.
let text: string = "Hi, Welcome to Itsourcecode!";
let matches: RegExpMatchArray | null = text.match(/Itsourcecode/);
console.log(matches);
Output:
Itsourcecode
15. search()
The search() method searches a string for a match against a regular expression and returns the position of the match.
let Samplestring = "Hi, Welcome to Itsourcecode!";
let re = /Itsourcecode/gi;
if (Samplestring.search(re) == -1) {
console.log("Not Found");
} else {
console.log("Found");
}
Output:
Found
16. slice():
The slice() method extracts parts of a string and returns the extracted parts in a new string.
let Samplestring = "Welcome to Itsourcecode!";
let newstr = Samplestring.slice(0,10);
console.log(newstr);
Output:
Welcome to
17. substr()
The substr() method is not a standard JavaScript method and might not work in all browsers. It’s recommended to use substring() or slice() instead.
18. substring()
The substring() method extracts characters from a string, between two specified indices, and returns the new sub string.
let Samplestring = "Welcome to Itsourcecode!";
let newstr = Samplestring.substring(0,15);
console.log(newstr);
Output:
Welcome to Itso
19. toLocaleLowerCase()
The toLocaleLowerCase() method converts a string to lowercase letters, according to the host’s locale.
let Samplestring = "Welcome to Itsourcecode!";
let newstr = Samplestring.toLocaleLowerCase();
console.log(newstr);
Output:
welcome to itsourcecode!
20. toLocaleUpperCase()
The toLocaleUpperCase() method converts a string to uppercase letters, according to the host’s locale.
let Samplestring = "Welcome to Itsourcecode!";
var newstr = Samplestring.toLocaleUpperCase();
console.log(newstr);
Output:
WELCOME TO ITSOURCECODE!
21. valueOf()
The valueOf() method returns the primitive value of a String object. It’s usually called automatically by JavaScript behind the scenes and not explicitly in code.
let Samplestring = new String("Welcome to Itsourcecode!");
let newstr = Samplestring.valueOf();
console.log(newstr);
Output:
Welcome to Itsourcecode!
Conclusion
Finally, we have finished discussing TypeScript Strings and their various methods with examples.
To recap, a string in TypeScript is a basic data type used to store textual data. String values are enclosed in either single (‘) or double (“) quotes.
I hope this article has helped you gain a better understanding of TypeScript Strings. If you have any questions or inquiries, please don’t hesitate to leave a comment below.