Open In App

How to check a string begins with some given characters/pattern ?

Last Updated : 21 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will check a string begins with some given characters/pattern. We can check whether a given string starts with the characters of the specified string or not by various methods in javascript which are described below.

Methods to check if a string begins with some given pattern:

Method 1: Using JavaScript loops

This is a simple approach in which we will match characters one by one from starting using the loop and if any character doesn’t match then we can say that string doesn’t begin with the character or specified string.

Syntax:

for (let i = 0; i < pattern.length; i++) {
        if(str.charAt(i) != pattern.charAt(i)){
            result = false;
            break;
        }
      }

Example: Below program demonstrates the above approach: 

javascript
// Javascript script to check
// whether the String begins
// with something or not

// Function to check String
// begins with something or not
function check (str, pattern) {
  // Initially we assume that String
  // begins with something
  // so result is true
  let result = true

  // Loop to match character by character
  for (let i = 0; i < pattern.length; i++) {
    // If any character doesn't matches
    // then result is false
    if (str.charAt(i) != pattern.charAt(i)) {
      result = false
      break
    }
  }

  if (result) {
    console.log('String begins with "' + pattern + '"')
  } else {
    console.log("String doesn't " + 'begins with "' + pattern + '"')
  }
}

// Driver code
// String to check
let str = 'GeeksforGeeks'

// Pattern by which string
// begins or not
let pattern = 'Geeks'

console.log('String = "' + str + '"')
console.log('String should begin with = "' + pattern + '"')

// Call check function
check(str, pattern)

// Change string
str = 'geeksforgeeks'

console.log('String = "' + str + '"')
console.log('String should begin with = "' + pattern + '"')

// Calling check function
check(str, pattern)

Output
String = "GeeksforGeeks"
String should begin with = "Geeks"
String begins with "Geeks"
String = "geeksforgeeks"
String should begin with = "Geeks"
String doesn't begins with "Geeks"

Method 2: Using substring() and localeCompare() Methods

In this method, we will use the substring() function to get a substring of the required length of the pattern string and then match the substring with a pattern using the localeCompare() function. 

Syntax:

let substr = string.substring(Startindex, Endindex)
string.localeCompare(substr)

Example: Below program demonstrates the above approach: 

javascript
// Javascript script to check
// whether the String begins
// with something or not

// Function to check String
// begins with something or not
function check (str, pattern) {
  // Extracting substring of
  // pattern length
  let sub_str = str.substring(0, pattern.length)

  if (sub_str.localeCompare(pattern) == 0) {
    console.log('String begins with "' + pattern + '"')
  } else {
    console.log("String doesn't " + 'begins with "' + pattern + '"')
  }
}

// Driver code
// String to check
let str = 'GeeksforGeeks'

// Pattern by which string
// begins or not
let pattern = 'Geeks'

console.log('String = "' + str + '"')
console.log('String should begin with = "' + pattern + '"')

// Call check function
check(str, pattern)

// Change string
str = 'geeksforgeeks'

console.log('String = "' + str + '"')
console.log('String should begin with = "' + pattern + '"')

// Calling check function
check(str, pattern)

Output
String = "GeeksforGeeks"
String should begin with = "Geeks"
String begins with "Geeks"
String = "geeksforgeeks"
String should begin with = "Geeks"
String doesn't begins with "Geeks"

Method 3: Using string startsWith() method

This is the best solution above all, in this method, we will use the startsWith() method to directly check whether the given string starts with something or not.

Syntax:

str.startsWith( searchString , position )

Example: Below program demonstrates the above approach: 

javascript
// Javascript script to check
// whether the String begins
// with something or not

// Function to check String
// begins with something or not
function check (str, pattern) {
  if (str.startsWith(pattern)) {
    console.log('String begins with "' + pattern + '"')
  } else {
    console.log("String doesn't " + 'begins with "' + pattern + '"')
  }
}

// Driver code
// String to check
let str = 'Burn to shine'

// Pattern by which string
// begins or not
let pattern = 'Burn'

console.log('String = "' + str + '"')
console.log('String should begin with = "' + pattern + '"')

// Call check function
check(str, pattern)

// Change string
str = 'Happy coding'
// Change pattern
pattern = 'happy'

console.log('String = "' + str + '"')
console.log('String should begin with = "' + pattern + '"')

// Calling check function
check(str, pattern)

Output
String = "Burn to shine"
String should begin with = "Burn"
String begins with "Burn"
String = "Happy coding"
String should begin with = "happy"
String doesn't begins with "happy"

Method 4: Using JavaScript indexOf() method

Example: In this example, we will use JavaScript string indexOf method to check if the pattern is present at index zero it returns true else it returns false

Javascript
// Javascript script to check
// whether the String begins
// with something or not

// Function to check String
// begins with something or not
function check (str, pattern) {
  if (str.indexOf(pattern) === 0) {
    console.log('String begins with "' + pattern + '"')
  } else {
    console.log("String doesn't " + 'begins with "' + pattern + '"')
  }
}

// Driver code
// String to check
let str = 'Burn to shine'

// Pattern by which string
// begins or not
let pattern = 'Burn'

console.log('String = "' + str + '"')
console.log('String should begin with = "' + pattern + '"')

// Call check function
check(str, pattern)

// Change string
str = 'Happy coding'
// Change pattern
pattern = 'happy'

console.log('String = "' + str + '"')
console.log('String should begin with = "' + pattern + '"')

// Calling check function
check(str, pattern)

Output
String = "Burn to shine"
String should begin with = "Burn"
String begins with "Burn"
String = "Happy coding"
String should begin with = "happy"
String doesn't begins with "happy"

Method 5: Using ES6 Destructuring and startsWith()

To check if a string begins with certain characters using ES6 destructuring and `startsWith()`, destructure the pattern into an array, then use `startsWith()` method to determine if the string begins with the specified pattern.

Example:

JavaScript
const str = "Hello world";
const [pattern] = ["Hello"];
const startsWithPattern = str.startsWith(pattern);
console.log(startsWithPattern); // Output: true

Output
true




Similar Reads

How to check a selector matches some content using jQuery?
In order to know whether the jQuery selector selected any element or not, Here 2 methods are discussed and these are mostly used methods. Example-1: In this example, Selector searches for &lt;p&gt; element. This example uses the length property to check If something is selected or not. In this case &lt;p&gt; element is found. &lt;!DOCTYPE html&gt;
2 min read
Explain some string functions of PHP
In the programming world, a string is considered a data type, which in general is a sequence of multiple characters that can contain whitespaces, numbers, characters, and special symbols. For example, "Hello World!", "ID-34#90" etc. PHP also allows single quotes(' ') for defining a string. Every programming language provides some in-built functions
7 min read
JavaScript typedArray.some() Method
The typedArray.some() is an inbuilt function in JavaScript which is used to check whether some elements of the typedArray satisfy the test implemented by the given function. Syntax: typedarray.some(callback) Parameters: It takes the parameter callback function and this callback function takes three parameters that are specified below- Value: It tak
2 min read
How to call a function automatically after waiting for some time using jQuery?
In order to run a function automatically after waiting for some time, we are using the jQuery delay() method. The .delay() method in jQuery which is used to set a timer to delay the execution of the next item in the queue.Syntax: $(selector).delay(para1, para2); Approach: When the Button is clicked the process is delayed to the specific time period
2 min read
How to select all elements that contains some specific CSS property using jQuery ?
Given a HTML document containing elements and some elements have specific CSS properties. The task is to select all elements having the same property value pair in them. There are two approaches that are discussed below: Approach 1: First select the elements in which we want to check for the same properties using jQuery Selector. Use filter() metho
3 min read
TypeScript Array some() Method
The Array.some() is an inbuilt TypeScript function which is used to check for some element in the array passes the test implemented by the provided function.Syntax: array.some(callback[, thisObject]) Parameter: This method accept two parameter as mentioned above and described below: callback : This parameter is the Function to test for each element
1 min read
How to validate if input in input field exactly equals to some other value using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In certain cases, we want the user to type some exact value and based on that we give the user access to the request or deny the r
5 min read
Some newly introduced array methods in JavaScript ES6
An array is used to store the elements of multiple data types in JavaScript altogether. Also, there are certain times when you have to manipulate the response received from the APIs as per the requirements on the webpages. Sometimes, the responses are objects and have to be converted to the arrays to perform the desired operations. These methods of
3 min read
Collect.js some() Method
The some() method is used to check whether the given collection contains a given item or not and returns the corresponding boolean value. Syntax: collect(array).some(key/value) Parameters: The collect() method takes one argument that is converted into the collection and then some() method is applied on it. The some() method holds the key/value as p
1 min read
Create a paragraph element with some text and append it to end of document body using jQuery
In this article, we will create a paragraph element with some text and append it to the end of the document body using jQuery. To append some text at the end of the document body, we use add() and appendTo() methods. The jQuery add() method is used to add elements to the existing group of elements. This method can add elements to the whole document
1 min read