Example 1: Check String Using Built-in Methods
Output
Enter a string: String The string starts with S but does not end with G
In the above program, the two methods startsWith() and endsWith() are used.
- The
startsWith()method checks if the string starts with the particular string. - The
endsWith()method checks if the string ends with the particular string.
The above program does not check for lowercase letters. Hence, here G and g are different.
You could also check if the above character starts with S or s and ends with G or g.
str.startsWith('S') || str.startsWith('s') && str.endsWith('G') || str.endsWith('g');
Example 2: Check The String Using Regex
Output
Enter a string: String The string starts with S and ends with G Enter a string: string The string starts with S and ends with G Enter a string: JavaScript The string does not start with S and does not end with G
In the above program, a regular expression (RegEx) is used with the test() method to check if the string starts with S and ends with G.
- The
/^S/ipattern checks if the string is S or s. Here,idenotes that the string is case-insensitive. Hence, S and s are considered the same. - The
/G$/ipatterns checks if the string is G or g. - The
if...else...ifstatement is used to check the conditions and display the outcome accordingly. - The
forloop is used to take different inputs from the user to show different cases.