Trending March 2024 # How If Statement Work In Typescript # Suggested April 2024 # Top 11 Popular

You are reading the article How If Statement Work In Typescript updated in March 2024 on the website Moimoishop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested April 2024 How If Statement Work In Typescript

Introduction to TypeScript if

Web development, programming languages, Software testing & others

Syntax:

In TypeScript, the superset of JavaScript so like that it has predefined functions, keywords and variables. Sometimes the user data’s are validating with the conditional statements like if, else etc. In TypeScript, the if statement will always return the boolean results.

if(boolean results) { }

The above codes are the basic syntax for utilising the if statement in the TypeScript. Based on the requirement analyses, the if statement will be called in the TypeScript in multi-tasking or big enterprise applications the nested if conditions are used to validate the user datas.

How if Statement Work in TypeScript?

In TypeScript, if-else is the one of the extensions and conditional loop statements for validating the user datas. The else block is one of the optional blocks in the programming languages; whenever the if condition is blocked, the loop will go to the else condition, so that if-else block facilitates the branching of the execution workflow into one or more number of blocks.

If we use some type of operators like boolean, ternary etc., like ternary operator they used the “?” symbol for to validate the user data, then the operands and operators are validating the datas using the if-else statement. An if-else statement will let the control for each execution of the statements based upon the conditional expressions also it includes the multiple else and if-clauses include else clause at each stage of the script always it return the boolean results for one conditional statement execution or multiple conditional statements execution.

If we use else if the clause in the script first executes if the statement is false, then it moves to else if the clause for execution so that the statement or statements will be executed and return the boolean result as true. We can also use nested if statements for the script.

Examples of TypeScript if

Given below are the examples of TypeScript if:

Example #1

Code:

var vars:string = "Welcome To My Domain your first input string kindly enter your datas" var vars1:string = "Welcome To My Domain your first input string kindly enter your datas" if(vars == "first"){ console.log("Your input is validated correctly") } else { console.log("Please try again.") } if(vars == vars1){ console.log("your both inputs are equal") } else { console.log("your both inputs are not equal") }

Output:

The first example we used if statement in different scenarios. We used two variables with string data values. We also validate the data, i.e.) we can compare the two variable values like vars and vars1 with conditional operators’ help; whatever we used in the operator, it will compare the operands and operators.

Example #2

Code:

var number = 6847; console.log(number + " Your inpur statement is executed and its valdiated the conditions Please provide your input on the actual text areas it will helpful for to validate its datas"); } else if (number < 0) { console.log(number + "Your inpur statement is not validated so the user inputs are not satisfied the conditions Please provide your input on the actual text areas it will helpful for to validate its datas"); } else { console.log(number + "Your inpur statement is not valid also your input datas are not valid in  the requirement conditions Please provide your input on the actual text areas it will helpful for to validate its datas"); } var vars="Welcome To My Domain Its a second example you have entered n number of datas for valdiating the input conditions so entered valid datas" if(vars == "Welcome To My Domain Its a second example you have entered n number of datas for valdiating the input conditions so entered valid datas") { console.log(vars + "Thanks for your input the application is validating your datas and after valdiation complete you move to next step"); } else{ console.log(vars + "Sorry User your input datas are not macthing the string conditions and also entered valid inputs and please try agian"); }

Output:

In the second example, we used the single variable with number datatype. We have initialised the variable value; that is, we declare any values that are related to the number. By using if statement, we have to check the string values by using the “==” operator and print the values with the help of the chúng tôi statement.

Example #3 var first = "Welcome To My Domain Please enter your inputs on the next line"; var last = "Its a Third example we used typeof, null and other pre-defined keywords"; var result= first + last; console.log(first); console.log(last); console.log(result); console.log(typeof first); console.log(typeof last); console.log(typeof result); console.log(null == undefined) console.log(null === undefined) if(first == null){ console.log('Welcome To My Domain Please enter your inputs on the next line'); } if(last == null){ console.log('Its a THird example we used typeof, null and other pre-defined keywords Please continue on this case'); } if(typeof result === 'undefined') { console.log('Its a Third example we used typeof, null and other pre-defined keywords Please continue on this case Please give your inputs on the exact input lines it will be useful for to validate your datas'); } else if(result === null){ console.log('Its a Third example we used typeof, null and other pre-defined keywords Please continue on this case'); }

Output:

In the final example, we used two variables with a nested if statement. So we have compare the variables with a different set of scenarios and pre-defined keywords. Additionally, we used “null, undefined” keywords for validating the conditions.

Rules and Regulations for if Statement

We validate the user data’s with a different set of scenarios like nested-if, if, else-if, else statement etc.

We used all the datatypes like integer or number, string, double etc.

Conclusion

In concluded part, generally, TypeScript has n number of keywords, variables and functions for creating the TypeScript application. For each type, we have used some conditional statements to validate the user data’s so that if it is one of the conditional statements, it will validate all the user data with a different type of data type.

Recommended Articles

We hope that this EDUCBA information on “TypeScript if” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading How If Statement Work In Typescript

How Select Statement Work In Sqlite?

Definition of SQLite select

SQLite select statement is the most important statement in SQLite, the select statement is used to fetch or retrieve data from the database. After execution of the select statement result will be zero or more rows from the table. The select statement just retrieves the data that means it is read-only by command and it does not make any changes to the database. Basically select statements return the result in a table and by using select statements we can perform the different operations as per our requirement. A SQLite select statement generally returns the derived content from the database but it can also be used to return the simple expression.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax

[where clause with specified expression] [group by clause with specified expression] [having with specified expression] [order by sort specified expression list] [limit integer [(offset) integer]]

In the above syntax, we use SQLite select statements to fetch desired records from the database with the help of different parameters as follows.

Distinct: when we use a distinct keyword in an SQLite statement then it returns only the distinct records from the database.

All: Sometimes we need to display all records from a specified table or database if it is duplicated at that time we can use all keywords.

Specified table name: Specified table means actual table name from which we want to fetch records.

Where clause with the expression: If we need to display particular records as per requirement at that time we can use where clause with custom expression to get required data from the tables.

Group by clause with the expression: If we need to combine multiple rows into a single row of output at that time we can use group by clause and specifically it is useful when results contain the aggregate functions.

Having expression: The working of ‘HAVING’ is similar to the ‘WHERE’ clause, the only difference is it comes after the group by clause.

Order by sort expression: The order by clause is used to sort the records as per requirement and display them by using SQLite select statement.

Limit integer: The limit keyword is used to set the limit on how many rows we need to display.

How select statement work in SQLite?

Now let’s see how the select statement is worked in SQLite as follows. Basically, there are different ways to use the SQLite select statement as follows.

1. From clause processing:

The information utilized by a straightforward SELECT query is a bunch of N rows every M column wide. If the FROM clause is removed from the select statement then input records are implicitly and solitary line zero segments wide (for example N=1 and M=0). If we specified a FROM clause in a select statement then the select statement comes from more than one table or we can say sub-queries that are specified from the keyword. If the FROM clause contains a single table or subquery at that time input records use the SQLite select statement. If a FROM clause contains more than one table or subquery at that time SQLite select statement uses JOIN constraint to get a combined result.

2. Where clause filtering:

On the off chance that a WHERE clause is indicated, the WHERE expression is assessed for each row in the records as a Boolean expression. Just lines for which the WHERE clause expression assesses to genuine are incorporated from the dataset prior to proceeding. Rows are prohibited from the outcome if the WHERE condition assesses to either false or NULL.

For a JOIN or INNER JOIN or CROSS JOIN, there is no contrast between a requirement expression in the WHERE condition and one in the ON clause. Sometimes, the difference between LEFT JOIN or LEFT OUTER JOIN is very important. In a LEFT JOIN, the additional NULL line for the right-hand table is added after ON provision preparing yet before WHERE condition handling.

3. Result generation set of rows:

When the result is filtered from the where clause then a simple SQLite select statement is calculated. This depends on whether the select statement is an aggregate or non-aggregate query or whether it is used group by clause or not.

Examples

Now let’s see the different examples of SQLite select statements as follows.

Simple uses of SQLite select statement as follows.

select 1 + 1;

Explanation

In the above example, we use a select statement with a mathematical expression that means we need to perform the addition of two numbers. The end out of the above statement we illustrated by using the following screenshot.

We can also perform multiplication and division by using SQLite statements as follows.

select 20 / 4, 4 * 4;

Explanation

In the above example, we perform division and multiplication of two numbers by using the SQLite statement. The end out of the above statement we illustrated by using the following screenshot.

Now let’s see how we can retrieve data from the table. So first create a new table by using the following statement as follows.

create table emp (emp_id integer, emp_name text not null, emp_dept text not null, emp_salary text not null);

Explanation

We successfully created a new table name as emp, now perform insert operation by using the following statement as follows.

insert into emp (emp_id, emp_name, emp_dept, emp_salary) values(1, "Johan", "COMP", "20000"), (2, "Sameer", "IT", "25000"), (3, "Jenny", "COMP", "15000"), (4, "Jay", "MECH", "12000");

Now perform different select statements as follows.

select * from emp;

The end out of the above statement we illustrated by using the following screenshot.

Suppose we need to display a particular column so that we can use the following statement as follows.

select emp_id, emp_dept, emp_salary from emp;

The end out of the above statement we illustrated by using the following screenshot.

Now see how we can use where, order by, and group by clause as follows.

select emp_id, emp_name, emp_dept, emp_salary from emp where emp_id =1 order by emp_name ASC;

Explanation

In the above example, we use a select statement with where and order by clause. The end out of the above statement we illustrated by using the following screenshot.

Similarly, we can use group by and having with select statements as per requirement.

Conclusion

We hope from this article you have understood about the SQLite select. From the above article, we have learned the basic syntax of select and we also see different examples of select. We also learned the rules of select. From this article, we learned how and when we use SQLite select.

Recommended Articles

We hope that this EDUCBA information on “SQLite select” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Case Statement Work In Sqlite?

Definition of SQLite CASE Statement

SQLite provides the case statement that means we can add case expression with conditional logic into the SQL statement. Basically, SQLite case expression executes the list of different conditions and it returns an expression that depends on the outcome of the execution. Working of SQLite case statements is the same as IF – THEN – ELSE statements like other programming languages. SQLite case statement we can use in any clause or SQL statement if the expression is valid, it included different clauses such as WHERE, ORDER BY, HAVING and SELECT as well as it also support the different SQL statement such as SELECT, UPDATE and DELETE. SQLite provides two different forms of the case statements.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

case specified test expression when [specified condition.1] then [specified expression. 1] when [specified condition.2] then [specified expression. 2] ………… when [specified condition. N] then [specified expression. N] else [specified expression] end

In the above syntax, we define more than one condition to get the required result. In the above syntax, we use when and then clauses and that work in an orderly manner. The execution above syntax is that it first executes condition 1 if this condition is true then it executes the expression 1 otherwise it will execute condition 2 and so on. If the condition is false then it will execute the else part of the syntax.

How CASE statement work in SQLite?

Now let’s see how the case statement works in SQLite as follows.

Normally there are two forms of the case statement in SQLite as follows.

SQLite simple case expression

The syntax of this we already mentioned in the above syntax. In this method, it compares each expression with the list of expressions to return the end output. This is a very simple method to execute the case statement as per the requirement of the user. Here each condition and each expression depends on each other that means if the first condition is true then and then only it executes expression, in this way it executes all conditions and expression and if a condition is false then control transfer to the else part as shown in the above syntax.

Search case expression

The search case expression assesses a rundown of expression to choose the outcome. Note that the straightforward case expression just analyzes for equity, while the looked-through case expression can utilize any type of examination.

Syntax:

case specified test expression when [specified Boolean expression.1] then [specified expression. 1] when [specified Boolean expression.2] then [specified expression. 2] else [specified expression] end

Search case expression assesses the Boolean expression in the grouping indicated and returns the relating result if the expression assesses to valid.

In the event that no expression assesses to valid, the search case expression returns the expression in the ELSE condition whenever indicated. In the event that you overlook the ELSE statement, the looked-through case expression brings NULL back.

Like the straightforward case expression, search case expression stops the assessment when the specified condition is met and execution will be stopped.

Example

Now let’s see the different examples of SQLite case statements as follows.

create table stud (stud_id integer primary key, stud_name text not null, stud_email text not null, stud_mark float not null);

Explanation

In the above example, we created a new table name as stud different attributes such as stud_id with integer data type and primary key, stud_name with text data type and not null, stud_email with text data type and not null, and stud_mark with float data type and not null constraint. End out of the above statement as shown in the below screenshot as follows.

.table

Now insert some records into the stud table by using insert into the statement as follows.

Explanation

With the help of the above statement, we inserted some records into the stud table successfully. End out of above statement as shown in below screenshot as follows.

Now use a simple SQLite case statement as follows.

select stud_id, stud_name, stud_mark, case else "You are Fail" end as "grade" from stud;

In the above example first, it check stud_mark greater than or equal to 85 if this condition is true then it shows A+, if condition false then it check second condition that is stud_mark greater than 70 then it shows A. if condition is false then control passes to third condition that is stud_mark greater than or equal to 60 then it shows B. if condition is false then it check stud_mark greater than or equal 50 then it shows C and if all condition is not satisfied then it execute the else part of above SQL statement that is You are Fail. End out of above statement as shown in below screenshot as follows.

Now let’s see the example of the second method that SQLite search case statement as follows.

We have an already created table that is stud, so directly use SQLite search case statement as follows.

select stud_id, stud_name, stud_mark, case else "C" end "grade" from stud;

Explanation

In the above example, we use a Boolean search case statement as shown in the above statement, here first check stud_mark greater than 86 then it prints A+. if the condition is false then is check the second condition that is stud_mark greater than 70 and stud_mark less than 60 then it prints A and if both conditions is false then it executes else statement. End out of above statement as shown in below screenshot as follows.

Conclusion

We hope from this article you have understood about the SQLite case. From the above article, we have learned the basic syntax of case statements and we also see different examples of case statements. We also learned the rules of case statements. From this article, we learned how and when we use the SQLite case statement.

Recommended Articles

We hope that this EDUCBA information on “SQLite CASE” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Nested If Statement In Python

Introduction to Nested IF Statement in Python

Programming has surely come a long way from a simple “Hello World” program to all the modern day’s complex programs. With time new features got added to programming to cater to various needs.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

So we need to introduce some sort of Decision making capability to our programs to make them more robust.

Let us suppose we have a program in which we input a number from the user and check whether it is an even number or an odd number. It is a classic example of using a conditional statement. The following flowchart would help depict it more clearly:-

Examples of Conditional Statements in Python

This is an example of an elementary conditional statement for finding whether a number is even or not.

The following are the different kinds of Conditional Statements in Python: –

if statement

if-else statement

else-if statement

nested if statement

switch statement

In this article, we would focus mainly on Nested If Statements, for which we would have a little introduction of If Statements, and then we would jump to the main topic.

1. If Statements

Syntax: –

Let us look into the details of the syntax of the if-statement.

The most important component is the “if” keyword, which helps us identify an expression to be a conditional statement.

expr: – This signifies the condition, the fulfillment of which would execute the below statement. The expr is basically a Python statement that results in a Boolean value (True or False). The statement for the particular expr will get executed only if the value for the expr is True.

statement: – This is the final part of the if-statement, which is the path along which the program must flow if the expr is True.

This is just a recap of the if-statement in Python as the nested if is an extension of the same.

2. Nested If Statements

A nested if is an if statement that is the target of a previous if statement. Let us look at the syntax of a nested if-statement.

# Executes statement1 when expr1 is True # Executes statement2 when expr2 is True # Inner if-block ends here # Outer if-block ends here

Let us look at the flow chart of nested if-statement to have a better understanding of it: –

In the following example, we implement the nested if-statement on a program where the user inputs a number and checks different conditions with regards to that number. Though the program is very simple, the only intention is to discuss the nested if-statements’ flow.

Code: 

a = 10 print("Inside initial if") print("Number is greater than 5") print("Inside first nested if") print("Number is greater than or equal to 10") print("Inside second nested if") print("Number is greater than or equal to 15") print("Outside second nested if") print("Outside second nested if") print("Outside initial if")

Output: –

The nested if must be properly indented, the failure of which results in Indentation Error as follows: –

a = 10 print("Greater than 7")

Output: –

Colon (:) must be follow all the ifs in the nested if-statements; otherwise, invalid syntax error would occur as follows:

Code:

a = 10 print("Greater than 7")

Output: 

Conclusion

It is finally time to draw closure to this article. In this article, we learnt the need for Conditional Statements in programming, touched upon the basics of if-statement with its syntax. Lastly, we discussed about nested if-statements in Python in details. I hope by now you guys are able to appreciate the usage of nested if-statements in Python. Now it is time to write your own Python program implementing the concepts learnt in this article.

Recommended Articles

This is a guide to the Nested IF Statement in Python. Here we discuss the Nested IF Statement in Python detailed discussion with examples and its Code Implementation. You can also go through our other suggested articles to learn more –

Working And Examples Of If Statement In React

Introduction to React If

For any coder or a Developer, applying If statements is one of the most basic skills they need. If statements are used to make behavioral changes in the product. For example, If a person’s age is above 18, he can drive a vehicle else; he is not eligible for driving. It also supports If statements. It comes under conditional rendering and is used just the way it is used in JavaScript. If a statement is used to match the condition, let the User Interface reaction be the basis of the user’s action. This article has covered some examples to help you understand how the If statement can be used to React to fulfill our requirements.

Start Your Free Software Development Course

Syntax

Working of If statement in React

As we can see in the above syntax of the If statement in React, Here, the age which the user provides is matched against the driving age, and if the user’s age fulfills the condition, then there is a success message; otherwise, the user is not eligible for driving. This was a basic example to understand the working of the If statement in React.

Examples of React If

Different examples are mentioned below:

Example #1 – Basic Example of React If

index.js (inside component folder)

import React from "react"; return ( ); }; return ( ); };

index.js (main file)

import React from "react"; import ReactDOM from "react-dom"; import { Button , Form } from "./components"; import "./styles.css"; class App extends React.Component { constructor(props) { super(props); this.state = { showForm: false }; } this.setState({ showForm: !this.state.showForm }); }; render() { let RenderedComponent; if (this.state.showForm) { } else { } } } const rootElement = document.getElementById("root");

chúng tôi

.App { font-family: times; text-align: center; }

Output:

Examples #2 – React If in a Form

Below we have made a registration form, where one can choose training according to one’s preference. The “If” statement is used so that no detail gets left unfilled. In the example below, we have used if statement in values.firstName, values.reception, values.street and values.pickupTime inside chúng tôi file.

chúng tôi

import React from 'react' import { render } from 'react-dom' import Styles from './Styles' import { Form , Field } from 'react-final-form' import pickupTimes from './pickupTimes' const sleep = resolve, ms) ) await sleep(300) window.alert(JSON.stringify(values, 0, 2)) } const Error = ( { name } { ( { meta: { error, touched } } } ) { ( { input: { value } } } ) Link to Our Website Please fill the below form so that we can customize the training and newsletter according to your Choices. <Form onSubmit={onSubmit} initialValues={{ EmploymentStatus: true, YourAdvisor: 'Rahul' }} const errors = {} if (!values.firstName) { errors.firstName = 'Required' } if (!values.reception) { errors.reception = 'Required' } if (values.reception === 'delivery') { if (!values.street) { errors.street = 'Required' } } else if (values.reception === 'pickup') { if (!values.pickupTime) { errors.pickupTime = 'Required' } } return errors }} > {({ handleSubmit , form , submitting , pristine <Field name="firstName" component="input" type="text" placeholder="Full Name" <Field name="reception" component="input" type="radio" value="liveinteractive" Live Interactive Training <Field name="reception" component="input" type="radio" value="selfpaced" Self Paced Training <Field name="street" component="input" type="text" placeholder="Your Address" {time} ))} <Field name="message" component="textarea" placeholder="Your Name" )} )

chúng tôi

import styled , { css } from 'styled-components' white-space: nowrap; display: inline-block; border-radius: 4px; padding: 4px 14px; font-size: 15px; color: #030303; &:visited { color: #baf573; } background-image: linear-gradient(${light}, ${dark}); border: 0.5px solid ${dark}; &:hover { background-image: linear-gradient(${light}, ${dark}); &[disabled] { background-image: linear-gradient(${light}, ${dark}); } } &:visited { color: #171716; } &[disabled] { opacity: 0.5; cursor: not-allowed; } const btnDefault = css` ${btn('#b5f7e3', '#e2f7b5')} color: #b7b8b4; const btnPrimary = btn('#d07dfa', '#7dd7fa') const btnDanger = btn('#eb6399', '#fcf586') export default styled.div` font-family: 'Times New Roman' , Times , serif; h1 { text-align: center; color: #cc235b; } h2 { text-align: center; color: #2623cc; } text-align: center; } a { display: block; text-align: center; color: #c780f2; margin-bottom: 9px; } p { max-width: 501px; margin: 9px auto; display: inline; } } .loading { font-size: 3em; font-weight: bold; text-align: center; margin: 49px; } form, div.form { text-align: left; max-width: 501px; margin: 9px auto; border: 0.5px solid #f58867; padding: 19px; box-shadow: 1px 1px 4px #f58867; border-radius: 2px; position: relative; display: flex; flex-flow: row nowrap; line-height: 1em; margin: 4px; position: relative; color: #ed4a96; width: 111px; min-width: 59px; font-size: 1.15em; line-height: 31px; } flex: 2; padding: 4px 6px; font-size: 1.15em; margin-left: 14px; border: 0.5px solid #7cf2e6; border-radius: 0.5px; } margin-top: 7px; } margin-left: 15px; margin-left: 0; display: block; margin-right: 2px; } } &.downshift { margin-left: 0; padding-left: 14px; flex: 1; width: 99%; padding: 5px 4px; font-size: 1.15em; margin-left: 0; border: 1.15px solid #d7f587; border-radius: 2px; } } } line-height: 29px; margin-left: 9px; color: #f52c2c; font-weight: bold; } ${btnDanger}; } } display: flex; flex-flow: row nowrap; justify-content: center; margin-top: 14px; } .error { display: flex; font-weight: bold; color: #f52c2c; flex-flow: row nowrap; justify-content: center; } pre { position: relative; border: 1.15px solid #e0faa5; background: #e6ff99; box-shadow: inset 2px 2px 2px #30302f; padding: 21px; } .submitting { display: block; position: absolute; top: -2px; left: -4px; right: -4px; padding: 0; text-align: center; background: #41423e; color: #f4f5f2; z-index: 11; font-weight: bold; font-size: 0.9em; } .saving { font-size: 0.9em; font-weight: bold; color: #516bed; margin: 9px 0 0 6px; } } button { margin: 0 9px; &[type='submit'] { ${btnPrimary}; } &[type='button'] { ${btnDefault}; } } .downshift-options { border: 2px solid #a0f2d8; box-shadow: 2px 2px 3px #1a1b1c; padding: 3px 5px; } } `

chúng tôi

const now = new Date(); let hours = now.getHours(); const times = []; if (now.getMinutes() < 30) { times.push(`${++hours}:30`); } else { hours++; } while (times.length < 6) { times.push(`${hours}:00`); times.push(`${hours}:30`); hours = ( hours + 1 ) % 24; } export default times;

Conclusion

Based on the above article, we understood the working of the If statement in React. Then, we went through a couple of examples to understand how an If statement can be used in different situations to change the behavior of the app according to the user’s action.

Recommended Articles

This is a guide to React If. Here we discuss the introduction, syntax, and working of the If statement in React along with examples and code implementation. You may also have a look at the following articles to learn more –

Learn The Examples Of Typescript Regex

Introduction to TypeScript RegEx

TypeScript RegEx is a Regular Expression object for matching text with some pattern. As TypeScript is also a part of JavaScript, similarly regular expressions are also the objects. TypeScript RegEx is the pattern matching standard for replacement and string parsing. These RegEx are used on various platforms and other programming environments. Since RegEx are language-independent, here, we will be discussing TypeScript RegEx. However, these Regular Expressions are now available for most of the Visual Basic and Visual Basic for Applications versions. Regular Expressions are used to find strings and replace them in a defined format. TypeScript Regular Expressions are also used to parse dates, email addresses, and urls, config files, log files, programming, or command-line scripts.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

In TypeScript, Regular Expressions or RegEx object can be done in 2 ways:

Using/ Calling a Constructor function of the Regular Expression Object.

Using a Regular Expression Literals.

Syntax:

Here in TypeScript, we use a Constructor function of the Regular Expression Object.

let regex = new  RegEx('bc*d')

Parameter: A pattern string is to be passed to the RegEx constructor object.

We can also use Literals for Regular Expressions,

let regex: RegEx = /bc*d/;

This syntax consists of any string pattern inside slashed.

Examples of TypeScript RegEx

Here are the following examples mention below

Example #1

RegEx using literals

Code:

let sampleRegEx: RegExp = /^[+ 0-9]{7}$/; console.log(sampleRegEx.test('732g')) console.log(sampleRegEx.test('453gh67')) console.log(sampleRegEx.test('2355575')) console.log(sampleRegEx.test('7878734')) console.log(sampleRegEx.test('423%^')) console.log(sampleRegEx.test('abcdefg')) console.log(sampleRegEx.test('@#$$#%5'))

Output:

Expression pattern [0-9] represents that the matching string should only contain numbers from 0 to 9 and only 7 digits are to be present in the string. Based on these conditions, the string checks with the expression and returns a Boolean value as true or false.

Example #2

RegEx matching for Email Address using RegEx constructor Object.

Code:

Output:

Example #3

Replacing string value with TypeScript RegEx

Code:

var regex = /apple/gi; var regexStr = "oranges are jucier than apple"; var newStr = regexStr.replace(regex, "mosambi");

Output:

Here, regex has a pattern ‘apple’. TypeScript Regex searches for the string ‘apple’ and replaces it with ‘mosambi’ using the string replace method and prints the complete string.

Let us get deeper on how to actually write a Regular Expression,

A TypeScript Regular Expression consists of simple characters as such, inside slashes / /. Expression such as /abcd/ or something which involves combination of special characters like /ab+c/ or complex expressions like /[a-z]+.%$d*/.

Simple patterns are constructed of characters to find a match directly. In example 3, we had directly searched for the word ‘apple’ and replaced using the word ‘mosambi’. Such matches will be useful to search for a word, replace it, or search for a substring. Even ‘space’ counts here. There is a lot of difference between the word ‘EducbaWebsite’ and ‘Educba Website’ if we search for the expression ‘ba W’.

Coming to Special characters, when a user searches for something more than a direct match like finding more than one g’s or finding digit 5 or any special character in the pattern. For example, Finding a single r followed by zero or more a followed by a digit, the pattern looks something like this; /ra*5/ Here * refers to zero or more a’s i.e the preceding item in the pattern.

Escaping: Used for Special Characters, If the user wants to have any kind of special characters in his pattern, the user needs to escape it by using a backslash in front of a special character. For example, to search for r followed by ^ and then at, backslash ‘’ will be used to ‘escape’ ‘^’ making it a literal instead of a special character. Pattern looks as, /r^t/

There is one more method to discuss in TypeScript RegEx, which is exec, this is used to search for a match in the specific string, returning the result of an array or a null. TypeScript RegEx objects are stateful when expressions have a global or a sticky flag set. Using exec, the user can loop over multiple matches in the input text.

Syntactically written as, regex.exec(string)

The string is the parameter passed to match the mentioned Regular Expression or the pattern. If there is a match found, exec() is a method that returns an array along with the index and the input text by further updating the last index of the object. If the matched text fails, the exec() returns null and the last index of the object is set to 0.

Example #4

TypeScript RegEx.exec()

Code:

const regexExec = RegExp('edu*', 'g'); const string = 'tutorial from educba, in the hindu education'; let arr; while ((arr = regexExec.exec(string)) !== null) { console.log(`Found ${arr[0]}, indexed at ${regexExec.lastIndex}.`); }

Output:

Here we searched for string ‘edu’ globally in the string above. Have declared a while condition saying if .exec(string) is not null, then return the index of the pattern found and set the last index.

Conclusion

With this, we conclude our topic ‘TypeScript RegEx’. We have seen what is TypeScript RegEx or also known as Regular Expression. We have seen how the syntax is and how it works, pulled out a few examples using both the literal method and the constructor object method in a way that will be understandable to all of you. Also have seen what are the types of expressions, Special character escaping, global object, and many more. Thanks! Happy Learning!!

Recommended Articles

We hope that this EDUCBA information on “TypeScript RegEx” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Update the detailed information about How If Statement Work In Typescript on the Moimoishop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!