How to Match Only the Exact Word Using Indexof or Includes in JavaScript

How to match only the exact word using indexOf or includes in JavaScript

To match the exact word you will have to use a regular expression.

/\bWidget\b/ will match the entire word.

In your example:

let str = "Widget";

if (str.search(/\bWidget\b/) >= 0) {
console.log( 'Found it!' );
}

javascript indexOf - exact match in a list / array

Thats wrong, you can use indexOf:

arr.indexOf(searchElement[, fromIndex = 0])

indexOf compares searchElement to elements of the Array using strict
equality (the same method used by the ===, or triple-equals, operator)

So ['eu', 'fr-CA', 'lt', 'sv', 'zh-CN', 'zh-TW'].indexOf('fr') returns -1.

indexOf / includes don't do an exact match and return false positives

I've never worked with Qualtrics before, but to me it is clear that the line

var fiveSampledNumbers = "${e://Field/five_sampled_numbers}";

will assign a string value to fiveSampledNumbers, not an array value.

Indeed, if you attempt to run the checks you are making on a string rather than an array, you get the unexpected results you saw above, because you are doing string operations rather than array operations:

var fiveSampledNumbers = "6,4,10,11,15";
console.log(fiveSampledNumbers.includes(5)); // logs true (string ends with the character "5")
console.log(fiveSampledNumbers.indexOf(5)); // logs 11 (index of the character "5")

To get around this, you will have to split the string by commas and parse each number within it:

var fiveSampledNumbers = "6,4,10,11,15";
fiveSampledNumbers = fiveSampledNumbers.split(",").map(function (n) { return parseInt(n, 10); });
console.log(fiveSampledNumbers.includes(5)); // logs false
console.log(fiveSampledNumbers.indexOf(5)); // logs -1

Filter out Certain Words and Match only EXACT Words

You need to use a RegExp to match every stock symbol in your list, but use the \b boundary symbol to prevent finding matches inside matches.

const string = 'TSLA will open green tomorrow.  LA will too.';
const symbols = ['T', 'S', 'LA', 'TSLA'];
const regExpString = String.raw`\b`+ symbols.join(String.raw`\b|\b`);
const regExp = new RegExp(regExpString, 'gi');
const matches = string.match(regExp);

console.log(matches); // [ 'TSLA', 'LA' ]

Javascript String Includes Exact Match without further matches

I also have an array of all possible colors (which I am not currently using in my logic) but have it available:

I think that's the problem. If some of the items there are substrings of other items, and you'd want only the other item to match if it exists in the input, then you need to include a check that the color you're looking for is the only one that exists in the input. Use .every to check that for every item in colorOptions, it's either the match argument, or it's not included in the alt:

let images = [  { id: 1, alt: "A Red Jacket" },  { id: 2, alt: "A Red Heather Jacket" },  { id: 3, alt: "A Red Heather Awesome Jacket" }];
let colorOptions = ["Red", "Red Heather", "Blue"];
function findMatch(array, match) { for (const item of array) { if ( item.alt.includes(match) && colorOptions.every(color => color === match || !item.alt.includes(color)) ) { item.color = match; } } return array;}
let redHeather = findMatch(images, "Red");console.log(redHeather);

Trying to find index of the exact word in an array instead of just the index of the first word that matches

There are a number of things which could be improved in what you have:

  • words in the scrambled version are different than the ones in the correct answer. If this is for some kids, I can picture them growing old, still playing, frustrated for not being able to crack it
  • you shouldn't perform DOM manipulations when using Vue. Not that it doesn't work, but Vue is quite a race car when it comes to handling and updating DOM efficiently. When you're doing it manually, it's a bit like getting down from driver's seat and pushing it down the road (simply update the source array and let Vue handle DOM based on value changes)
  • when handling drag and drop, you need unique identifiers for your elements. Their current index will suffice. (.indexOf() returns the first element matching the condition - that's why your compare method fails).

Here it is:

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: () => ({
to: "",
from: "",
words: [],
verse: "Genesis 1:1",
correctAnswer: "In the beginning God created the heavens and the earth"
}),
computed: {
isCorrectOrder() {
return this.words.join(' ') === this.correctAnswer;
}
},
methods: {
onDragEnd() {
const word = this.words[this.from];
this.words.splice(this.from, 1);
this.words.splice(this.to, 0, word);
},
},
mounted() {
// basic shuffle
this.words = this.correctAnswer.split(" ")
.map(s => ({s, r: Math.random()}))
.sort((a, b) => a.r > b.r ? -1 : 1)
.map(o => o.s);
},
})
ul {
list-style: none;
font-size: 24px;
display: flex;
justify-content: space-evenly;
padding-left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="( value, index ) in words"
:key="index"
draggable="true"
@drag="from = index"
@dragover.prevent="to = index"
@dragend.prevent="onDragEnd"
v-text="value" />
</ul>
<div :verse="verse">- {{ verse }}</div>

<h4><em v-if="isCorrectOrder">You got it right!</em></h4>
</div>

IndexOf Returning Partial Match

You could try using findIndexOf or in your case just find should do the trick, or even includes.

Something like this:

if(finalArr.includes(rec.name){
continue;
}

includes is great for a simple string match. If you want greater matching then you can try find. find will let you compare each element in the array against a certain condition and you can perform multiple checks on it.

if(!!finalArr.find(element => (element.toLowerCase() === name.rec.toLowerCase()){
continue;
}

I would, however, definitely recommend against converting your array to a string and trying to search it, especially for this case.

How to check if a string contain specific words?

If you are looking for exact words and don't want it to match things like "nightmare" (which is probably what you need), you can use a regex:

/\bare\b/gi

\b = word boundary
g = global
i = case insensitive (if needed)

If you just want to find the characters "are", then use indexOf.

If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test.



Related Topics



Leave a reply



Submit