Strings in TypeScript – Part 2

Strings in TypeScript is divided in three parts:

This section has the details of following methods:

subString subStr split
slice search replace
match localeCompare lastIndexOf
lastIndexOf()

This method returns the last index of a specified value within a string. Search will start from the starting of the string. variable is the string in which we are searching for the value.
searchString is the value which we are searching in the variable.
fromIndex is an integer which specify the starting index for the search. It will return -1 if the string is not found.
Syntax

variable.lastIndexOf(searchString, [fromIndex])

Below is a sample code

var str1 = new String("This is a sample string sample");
console.log("Last Index of i: " + str1.lastIndexOf('i'));
console.log("Last Index of is: " + str1.lastIndexOf("is"));
console.log("Last Index of sample: " + str1.lastIndexOf("sample"));
console.log("Last Index of sample: " + str1.lastIndexOf("sample", 14));
console.log("Last Index of two: " + str1.lastIndexOf("two"));

Below is the output of above code

localeCompare()

This method will return an integer value after sorting two strings
Syntax

str1.localeCompare(str2);

– Returns 0 if str1 and str2 are equal.
– Returns 1 if str2 comes before str1 in the locale sort order.
– Returns -1 if str2 comes after str1 in locale sort order.

Below is an example

var str1 = new String("ab");
var str2 = new String("cd");    
var index1 = str1.localeCompare("ab");  
var index2 = str2.localeCompare("ab");  
var index3 = str1.localeCompare("cd"); 
console.log("Perfect Match: " + index1 );
console.log("Parameter value comes before the string value: " + index2 );
console.log("Parameter value comes after the string value: " + index3 );

Below is the output of above code

match()

This method searches a string for a match against a regular expression. This will return an array of all matches. Include g modifier to do a global search, that is in complete string. Otherwise it will return only the first match in the string. i is used to match without case-comparison. This method will return null if no match is found.
Syntax

variable.match(regexpre);

Below is an example

var str1 = new String("This is an example. ThiS IS good.");
console.log(str1.match(/is/g));
console.log(str1.match(/is/gi));

Below is the output of above code

replace

This method first finds a match between a regular expression and a string, then replaces the matched substring with another substring.
Syntax

variable.replace(regexp, substring);

Below is a sample code

var str1 = new String("I like to eat mangoes, but mangoes only come in summers. Mangoes are yellow in color.");
var result = str1.replace(/mangoes/gi,"apples");
console.log(result);

Below is the output of above code

This method searches a substring, using a regular expression, within a string and returns the index.
If the regular expression is not inside the string, it will return -1.
Syntax

string.search(regexp);

Below is a sample code

var str1 = new String("I like to eat mangoes, but mangoes only come in summers. Mangoes are yellow in color.");
var index = str1.search(/mangoes/gi);
console.log("First index of mangoes: " + index);

Below is the output of above code

slice()

This method extracts a section of a string and returns a new string. You can remove characters from beginning as well as from the end of the string. Giving the value fromEnd is optional.
Syntax

string.slice(fromBeginning, [fromEnd]);

Below is an example

var str1 = new String("I like to eat mangoes, but mangoes only come in summers.");
console.log(str1.slice(4,-5));

Below is the output of above code

split

This will split a string into array based on a substring. This method returns an array.
separator is the substring used to split a string.
limitOfValues is an integer value that tells how many values to return.
Syntax

string.spli(separator, [limitOfValues])

Below is an example

var str1 = new String("red,orange,blue,black,yellow,green");
var colors = str1.split(',');
var i:number;
console.log("All color values");
for(i=0; i<colors.length; i++)
{
    console.log(colors[i]);
}
var colors1 = str1.split(',',3);
var i:number;
console.log("\nOnly 3 color values");
for(i=0; i&lt;colors1.length; i++)
{
    console.log(colors1[i]);
}

Below is the output of above code

substr()

This method will return a new string.
startIndex represents the index from where we want to start extracting the substring.
length is a number representing the number of characters we want to extract. This is optional.
Syntax

string.substr(startIndex, [length]);

Below is a an example

var str1 = new String("I like to eat mangoes, which are yellow in color");
console.log("Original String: " + str1);
console.log("(0): " + str1.substr(0));
console.log("(4): " + str1.substr(4));
console.log("(5,9): " + str1.substr(5,9));
console.log("(-2): " + str1.substr(-2));
console.log("(-5,4):" + str1.substr(-5,4));

Below is the output of above code

substring()

This method will return a new string between two indexes. It does not take negative values like we used in substr() method, hence we cannot start extraction from the end of the string.
startIndex is the starting index from where the extraction should begin
endIndex is the index where the extraction should end. This is optional.
Syntax

string.substring(startIndex,[endIndex]);

Below is an example

var str1 = new String("I like to eat mangoes, which are yellow in color");
console.log("Original String: " + str1);
console.log("(0): " + str1.substring(0));
console.log("(4): " + str1.substring(4));
console.log("(5,9): " + str1.substring(5,9));
console.log("(-2): " + str1.substring(-2));
console.log("(-5,4): " + str1.substring(-5,4));

Below is the output of the above code

Strings in C#

String is nothing but a collection of characters be it collection of alphabets, alphanumeric or include special symbols. String is always enclosed within double quotes. Examples of String are: “Hello”,”Hello World!”,”P@ssw0rd2018″ etc.

We can do lots of manipulation on these string values. System.String provides a number of methods that we can use to manipulate these values. Lets see how to do that. I am creating a Console Application StringDemo.

Assign value to a string variable:

String value = "Hello World";

Concat()
We can concatenate two or more string values in one using plus (+) sign or using
Concat function.

String val1 = "My name is";
String val2 = "David";
String val3 = "Miller";
String val4 = val1 + " " + val2 + "!";
Console.WriteLine("Concatenated Value using + sign: " + val1 + " " + val2);
Console.WriteLine("Value of val4: " + val4);
String val5 = String.Concat(val1, " ",val2, " ", val3);
Console.WriteLine("Concatenated value using Concat function: " + val5);

Below is the result of the above code:

Length
Length is used to calculate the number of characters that are there in the string. It also counts the space characters. Result of below code is:

String value = "Hello World";
Console.WriteLine("Length of " + value + "is: " + value.Length);

Below is the result of the above code:

Compare()
C# is case-sensitive. Hence Hello is different from hello. Compare function is used to compare two strings. This function returns an integer value. If this returns 0, he values are same. If this returns 1, values are different. Below is the sample code:

String val1 = "Hello";
String val2 = "Hello";
String val3 = "hello";
int result = String.Compare(val1, val3);
int result1 = String.Compare(val1, val2);
int result2 = String.Compare(val1, val3, true);
Console.WriteLine("Comparison of Hello and hello: " + result);
Console.WriteLine("Comparison of Hello and Hello: " + result1);
Console.WriteLine("Comparison of Hello and hello, ignored the case: " + result2);

Below is the result of the above code:

Contains()
This method determines whether a string contains a specified substring. It will return a bool value, either true or false.
Below is a sample code:

String val = "Hello World";
bool result = val.Contains("Wor");
bool result1 = val.Contains("Hi");
Console.WriteLine("Hello World contains Wor? " + result);
Console.WriteLine("Hello World contains Hi? " + result1);

Below is the result of the above code:

Insert()
Insert() method inserts a specified string within a string at a given index. The index starts with 0.

String original = "HelloWorld!";
Console.WriteLine("The original string: '{0}'", original);
String updated = original.Insert(5, " ");
Console.WriteLine("The modified string: '{0}'", updated);
String updated1 = original.Insert(5, " Big ");
Console.WriteLine("The modified string: '{0}'", updated1);

Below is the result of above code:

PadLeft(), PadRight()
These methods are used to pad a character either left or right of a string.
Below is the sample code:

String name = "David";
char char1 = '*';
Console.WriteLine(name.PadLeft(15, char1));
Console.WriteLine(name.PadLeft(3, char1));
Console.WriteLine(name.PadRight(15, char1));
Console.WriteLine(name.PadRight(6, char1));

Below is the output of above code:

Insert(), Remove(), Replace()
Insert() method is used to insert a given string into another string at a specific index.
Remove() method is used to delete a specified number of characters from a specified string.
Replace() method is used to replace all occurrences of a specified character with another character in a specified string.
Below is the sample code for above method:

String str = "Hello World!";
Console.WriteLine("str = " + str);
Console.WriteLine("str.Insert(6, \"Hi \") : " + str.Insert(6, "Hi "));
Console.WriteLine("str.Remove(7,2) : " + str.Remove(7,2));
Console.WriteLine("str.Remove(7) : " + str.Remove(7));
Console.WriteLine("str.Replace(7,2) : " + str.Replace('l','*'));
Console.WriteLine("str.Replace(\"ll\",\"12\") : " + str.Replace("ll","12"));

Below is the result of above code:

Split()
This method is used to split a string in an array.
Below is the sample code for above method:

String str = "Orange,Yellow,Red,Green,Blue";
String[] colors=str.Split(',');
Console.WriteLine("str: " + str);
Console.WriteLine("Split character: \',\'");
Console.WriteLine();
Console.WriteLine("Result after splitting the string using \"str.Split(\',\')\"");
foreach(String s in colors)
{
    Console.WriteLine(s);
}

Below is the result of the above code:

Trim()
Trim() removes all the leading and trailing white-space characters from the string.
Below is the sample code:

String str = " Hello World ";
Console.WriteLine("str: " + str + "!");
Console.WriteLine("str.Trim(): " + str.Trim() + "!");

Below is the result of above code:

ToUpper(), ToLower()
ToUpper() is used to convert the complete string in upper-case.
ToLower() is used to convert the complete string in lower-case.
Below is the sample code:

String str = "Hello World!";
Console.WriteLine("str: " + str);
Console.WriteLine("str.ToUpper() : " + str.ToUpper());
Console.WriteLine("str.ToLower() : " + str.ToLower());

Below is the output of above code:

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started