• Skip to main content
  • Skip to primary sidebar
  • Home
  • Angular
  • ASP.NET Core
  • Entity Framework
    • Entity Framework 6
    • Entity Framework Core
  • Crystal Reports
  • C#
  • ASP.NET
  • About Us
    • Privacy Policy
    • Contact Us

TekTutorialsHub

Free Online Tutorials

TypeScript String

September 13, 2019 by TekTutorialsHub Leave a Comment

Type Inference
Template Literals/Strings

We use Typescript string to store the textual data. It is a primitive data type in typescript. We enclose string data in double-quotes (“) or single quotes (‘). We can also define them using the Template literal syntax or back-tick. Such strings are called Template strings, The Template strings can be used to create multi-line strings, strings with embedded expressions & Tagged Template strings. The Typescript also has a String object, which is a wrapper around a primitive string. In this tutorial, we learn about typescript strings. We also find out the difference between String vs string. Finally, we also look at the list of typescript string functions.

Table of Content

  • Defining Strings
    • Single Quote
    • Double Quote
    • String Function
    • Template Literal (Template String)
  • Long single-line strings
  • string vs String
  • String Functions
    • Methods
    • HTML Related Methods
  • Summary

Defining Strings

There are four ways to define a primitive string.

  1. Single Quote
  2. Double Quote
  3. Using Global String function
  4. Template literal syntax or back-tick

Single Quote

Example:

1
2
3
4
5
6
7
8
9
 
let message='Hello World';       //in single quote
console.log(message);
console.log(typeof(message))
 
***output***
Hello World
string
 

Double Quote

Example:

1
2
3
4
5
6
7
8
9
 
let color="red";             //in double quote
console.log(color);
console.log(typeof(color))
 
*** output ***
red
string
 

String Function

We can also use the global String function to create a primitive string as shown below.

1
2
3
4
5
6
7
8
9
 
let color=String("red");
console.log(color);
console.log(typeof(color))
 
**** output ****
red
string
 

Template Literal (Template String)

The Template Literal or Template strings are strings, which are enclosed in a back-tick (`). They bring several other features like

  1. Multiline string
  2. String interpolation
  3. Embedded Template Variable
  4. Tagged Templates

The following is an example of a multiline string.

1
2
3
4
5
6
7
8
9
10
 
character let sentence: string =`Hello, welcome to the world of typescript,
          the typed super of javascript`
console.log(sentence);
 
 
***output ****
Hello, welcome to the world of typescript,
the typed super of javascript
 

Long single-line strings

The long single line strings take up the entire screen width. You can break them into multiple lines using the + operator. This is the preferred way of writing long single line strings.

1
2
3
4
5
6
7
8
9
10
11
12
 
let longString = "This is an example of long single line of string and it goes out of my editor screen so i need to wrap it";
 
let longString1 = "This is an example of long single line of string "+
              "and it goes out of my editor screen "+
              "so i need to wrap it";
console.log(longString1)
 
 
*** output ***
This is an example of long single line of string and it goes out of my editor screen so i need to wrap it
 

Another way is to use the \ at the end of the line, which indicates that the line continues on the next line.

1
2
3
4
5
6
7
8
9
 
let longString2 = "This is an example of long single line of string \
and it goes out of my editor screen \
so i need to wrap it";
console.log(longString2)
 
*** output ***
This is an example of long single line of string and it goes out of my editor screen so i need to wrap it
 

Any leading spaces also become part of thestring.

1
2
3
4
5
6
7
8
9
10
 
let longString2 = "This is an example of long single line of string \
    and it goes out of my editor screen \
    so i need to wrap it";
console.log(longString2)
 
 
*** output ***
This is an example of long single line of string     and it goes out of my editor screen     so i need to wrap it
 

string vs String

The Typescript has two string data types. The one is a string (lowercase) & the other one is String (S is uppercase)

The string is a primitive data type. It is the one you must use. The primitive data type does not have properties or methods.

The String is a wrapper object around string. It is created by using the syntax new String(""). The objects have properties or methods.

1
2
3
4
5
6
7
8
9
 
var str1= new String("Created with String")     //str1 is a String object
console.log(str1);
console.log(typeof(str1))
 
**** output ****
[String: 'Created with String']
object
 

String object cannot be assigned to a primitive string.

1
2
3
4
5
6
7
8
9
10
11
 
var strPrim = "I am primitive";             //strPrim is a string pimitive type
var strObj= new String("I am a object")     //strObj is a String object
 
strPrim=strObj;     //Compiler error here.
 
 
**** Error ***
Type 'String' is not assignable to type 'string'.
  'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.ts(2322)
 

Primitive string can be assigned to a String object.

1
2
3
4
5
6
7
 
var strPrim = "I am primitive";             //strPrim is a string pimitive type
var strObj= new String("I am a object")     //strObj is a String object
 
 
strObj=strPrim;    //ok
 

String global object creates a primitive string. String object can be created only with new String().

1
2
3
4
5
6
7
8
9
10
11
 
var strPrim = "I am primitive";             //primitive
var strGlb=String("I am a primitive string created using String method")  //primitive
var strObj= new String("I am a object")    //object
 
 
console.log(typeof(strPrim))   //string
console.log(typeof(strGlb))    //string
console.log(typeof(strObj))   //object
 
 

String Functions

As mentioned earlier, the strings are primitive types and do not support methods & properties. But as shown in the following example shows it has a method indexOf.

1
2
3
4
5
6
7
8
 
let strValue="This is a primitive string. But is has properties & methods"
let pos=strValue.indexOf("primitive")
console.log(pos);
 
***output***
10
 

That is because string primitives are coerced into a String object in order to access the method indexOf. The object is used only for temporarily and garbage collected once the method call is returned.

Methods

MethodDescription
charAtReturns the character at the specified index.

@param pos — The zero-based index of the desired character
charCodeAtReturns the Unicode value of the character at the specified location.

@param index — The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.
codePointAteturns a nonnegative integer Number less than 1114112 (0x110000) that is the code point value of the UTF-16 encoded code point starting at the string element at position pos in the String resulting from converting this object to a String. If there is no element at that position, the result is undefined. If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
concatReturns a string that contains the concatenation of two or more strings.

@param strings — The strings to append to the end of the string.
endsWithReturns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at endPosition – length(this). Otherwise returns false.
includesReturns true if searchString appears as a substring of the result of converting this object to a String, at one or more positions that are greater than or equal to position; otherwise, returns false.

@param searchString — search string

@param position — If position is undefined, 0 is assumed, so as to search all of the String.
indexOfReturns the position of the first occurrence of a substring.

@param searchString — The substring to search for in the string

@param position — The index at which to begin searching the String object. If omitted, search starts at the beginning of the string
lastIndexOfReturns the last occurrence of a substring in the string.

@param searchString — The substring to search for.

@param position — The index at which to begin searching. If omitted, the search begins at the end of the string.
lengthReturns the length of a String object.
localeCompareDetermines whether two strings are equivalent in the current locale.

@param that — String to compare to target string
matchMatches a string with a regular expression, and returns an array containing the results of that search.

@param regexp — A variable name or string literal containing the regular expression pattern and flags.
normalizeReturns the String value result of normalizing the string into the normalization form named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.

@param form — Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default is "NFC"
repeatReturns a String value that is made from count copies appended together. If count is 0, the empty string is returned.

@param count — number of copies to append
replaceReplaces text in a string, using a regular expression or search string.

@param searchValue — A string to search for.

@param replaceValue — A string containing the text to replace for every successful match of searchValue in this string.
searchFinds the first substring match in a regular expression search.

@param regexp — The regular expression pattern and applicable flags.
sliceReturns a section of a string.

@param start — The index to the beginning of the specified portion of stringObj.

@param end — The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. If this value is not specified, the substring continues to the end of stringObj.
splitSplit a string into substrings using the specified separator and return them as an array.

@param separator — A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.

@param limit — A value used to limit the number of elements returned in the array.
startsWithReturns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.
substrGets a substring beginning at the specified location and having the specified length.

@param from — The starting position of the desired substring. The index of the first character in the string is zero.

@param length — The number of characters to include in the returned substring.
substringReturns the substring at the specified location within a String object.

@param start — The zero-based index number indicating the beginning of the substring.

@param end — Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. If end is omitted, the characters from start through the end of the original string are returned.
toLocaleLowerCaseConverts all alphabetic characters to lowercase, taking into account the host environment's current locale.
toLocaleUpperCaseReturns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale
toLowerCaseConverts all the alphabetic characters in a string to lowercase
toStringReturns a string representation of a string.
toUpperCaseConverts all the alphabetic characters in a string to uppercase
trimRemoves the leading and trailing white space and line terminator characters from a string.
valueOfReturns the primitive value of the specified object.

HTML Related Methods

MethodDescription
anchorReturns an <a> HTML anchor element and sets the name attribute to the text value

@param name
bigReturns a <big> HTML element
blinkReturns a <blink> HTML element
boldReturns a <b> HTML element
fixedReturns a <tt> HTML element
fontcolorReturns a <font> HTML element and sets the color attribute value
fontsizeReturns a <font> HTML element and sets the size attribute value
italicsReturns an <i> HTML element
linkReturns an <a> HTML element and sets the href attribute value
smallReturns a <small> HTML element
strikeReturns a <strike> HTML element
subReturns a <sub> HTML element
supReturns a <sup > HTML element

Summary

The Typescript string is a primitive data type. The String is an object which is a wrapper around primitive string We can use single quote, double quote, global string function or use template literal syntax to create a primitive string. We use template literal syntax to create multi-line strings, strings with embedded expressions & Tagged Template strings, etc.

Type Inference
Template Literals/Strings

Filed Under: TypeScript Tagged With: Typescript Strings

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Typescript Tutorial

Getting Started

  1. Introduction To TypeScript
  2. TypeScript Installation and Environment Setup
  3. TypeScript Hello World Example
  4. Enable Compile on Save in Visual Studio Code
  5. Syntax and Basic Rules

Typescript Basics

  1. Typescript Data Types
  2. Type Annotations
  3. Variable Declaration
  4. Identifiers & keywords
  5. Variable Scope
  6. Let, Var & Const
  7. Constants
  8. Type Inference

Strings

  1. String Data Type
  2. Template strings/Literal strings
  3. Tagged Templates

Numbers

  1. Number Data Type
  2. NaN in Typescript
  3. Min, Max & Safe Values
  4. EPSILON & Floating Point Precision
  5. Infinity

BigInt

  1. BigInt data type
  2. BigInt Vs Number

Boolean

  1. Boolean Data Type

 

 

Copyright ©2008-2018

About us Contact Privacy Policy

Dec,08,2019 05:43:16 AM