Skip to content

Instantly share code, notes, and snippets.

@xettri
Created September 17, 2024 08:29
Show Gist options
  • Save xettri/63f5e104d2906012d3a366b13faa579f to your computer and use it in GitHub Desktop.
Save xettri/63f5e104d2906012d3a366b13faa579f to your computer and use it in GitHub Desktop.
// Solution 1 without regex
function isLowerAlpha(char) {
return /^[a-z]+$/.test(char);
}
function getWordPos(word, text) {
for (var i = 0; i <= text.length - word.length; i++) {
if (text.substr(i, word.length) === word) {
if (i === 0 || !isLowerAlpha(text.charAt(i - 1))) {
if (
i + word.length === text.length ||
!isLowerAlpha(text.charAt(i + word.length))
) {
return i;
}
}
}
}
return -1;
}
// Solution 2 regex
function getWordPos(word, text) {
const filterText = text.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
const parts = filterText.split(/\s+/);
for (let i = 0; i < parts.length; i++) {
if (parts[i] === word) {
const match = new RegExp(`\\b${word}\\b`, "g").exec(text);
return match ? match.index : -1;
}
}
return -1;
}
function runPlainTest(arr) {
arr.forEach((val) => {
const res = getWordPos(val.word, val.text);
if (res !== val.result) {
throw new Error(
`Test faild for ${JSON.stringify(val, null, 2)}` +
`\nexpected ${res} but passed ${val.result}`
);
}
});
console.log("All test cases passed!!");
}
const testSamples = [
{
word: "is",
text: "this !!is a string",
result: 7,
},
{
word: "is",
text: "this (is a string",
result: 6,
},
{
word: "is",
text: "this (is) a string",
result: 6,
},
{
word: "is",
text: "this is a string",
result: 6,
},
{
word: "is",
text: "this is a string",
result: 5,
},
{
word: "not",
text: "this is a string",
result: -1,
},
{
word: "string",
text: "this is a string",
result: 10,
},
{
word: " ",
text: "this is a string",
result: -1,
},
];
runPlainTest(testSamples);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment