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:
- RegExp can be used to describe the pattern to test against the given string. Starting from the beginning with the marker
^
, we expect the charactersix
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
);
- 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
);
function mixStart(str) {
return str.slice(1, 3) === "ix";
}
//Examples
console.log(
mixStart('mix snacks') // → true
,
mixStart('pix snacks') // → true
,
mixStart('piz snacks') // → false
);