Home > other >  Is there a better way of checking if the characters in index 1 and 2 match a particular requirement?
Is there a better way of checking if the characters in index 1 and 2 match a particular requirement?

Time:01-02

I am new to learning JavaScript. I just wondered if there is a better way of checking for a particular string starting from index 1.

This is how I solved the problem so far:

function mixStart(str) {
  if (str[1] === 'i' && str[2] === 'x') {
    return true;
  } else {
    return false;
  }
}

//Examples
console.log(
  mixStart('mix snacks') // → true
,
  mixStart('pix snacks') // → true
,
  mixStart('piz snacks') // → false
);

CodePudding user response:

Yes, You can use String.prototype.startsWith() to check if a string starts with a specific substring from a specific index.

For example, you can rewrite your code like this:

function mixStart(str) {
  return str.startsWith('ix', 1);
}

This will return true if the string starts with the substring 'ix' from index 1, and false otherwise.

Here's an example of how you can use the startsWith() method:

console.log('mix snacks'.startsWith('ix', 1)); // → true
console.log('pix snacks'.startsWith('ix', 1)); // → true
console.log('piz snacks'.startsWith('ix', 1)); // → false

CodePudding user response:

const mixStart = (str) => str.slice(1,3) === "ix"

//Examples
console.log(
  mixStart('mix snacks') // → true
,
  mixStart('pix snacks') // → true
,
  mixStart('piz snacks') // → false
);

CodePudding user response:

There are several alternatives:

  1. RegExp can be used to describe the pattern to test against the given string. Starting from the beginning with the marker ^, we expect the characters ix after a first character (represented by .):

function mixStart(str) {
  return /^.ix/.test(str);
}

//Examples
console.log(
  mixStart('mix snacks') // → true
,
  mixStart('pix snacks') // → true
,
  mixStart('piz snacks') // → false
);

  1. As pointed by Alireza Amini, you can rely on startsWith to check the start of your string, given an offset as second parameter to start from character 2:

function mixStart(str) {
  return str.startsWith("ix", 1);
}

//Examples
console.log(
  mixStart('mix snacks') // → true
,
  mixStart('pix snacks') // → true
,
  mixStart('piz snacks') // → false
);

  1. As pointed by DanteDX, you can extract the substring to check with slice:

function mixStart(str) {
  return str.slice(1, 3) === "ix";
}

//Examples
console.log(
  mixStart('mix snacks') // → true
,
  mixStart('pix snacks') // → true
,
  mixStart('piz snacks') // → false
);

  • Related