Mr. Goose
Mr. Goose

Reputation: 55

Check string includes a substring without extra characters?

I am trying to get my code to sort through two arrays and create a dictionary that contains values from both, but when I search through them I end up getting extra values that I don't want. For example while searching through 'USD' symbols, I can end up with XXX-USDT when I specifically want USD, not USDT. How can I make sure there aren't extra characters before or after?

var symbols = ['ETH', 'BTC', 'USD', 'USDT'];
var marketPairs = ['AAVE-USD', 'AAVE-USDT', 'AAVE-BTC', 'AAVE-ETH'];

var marketDict = {};

for (let i = 0; i < symbols.length; i++) {
    marketDict[symbols[i]] = [];
    for (let j = 0; j < marketPairs.length; j++) {
        if (marketPairs[j].includes('-'+symbols[i]) || marketPairs[j].includes(symbols[i]+'-')) {
            marketDict[symbols[i]].push(marketPairs[j]);
        }
    }
}

Upvotes: 0

Views: 147

Answers (2)

Constantin Buruiana
Constantin Buruiana

Reputation: 65

Your if condition checks if a string contains -USD, not if it exactly matches it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

If you're looking to match the end/start of the string, you can use .endsWith and startsWith:

if (marketPairs[j].endsWith('-'+symbols[i]) || marketPairs[j].startsWith(symbols[i]+'-'))

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith for reference)

Alternatively, you can use RegEx in combination with .search (if you want to get an array of matched chars) or .match (if you just want an index of the first match):

if (marketPairs[j].match(new RegExp(symbols[i] + '|' + symbols[j])) > -1)

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)

Upvotes: 1

DecPK
DecPK

Reputation: 25408

You can use endsWith and startsWith here

marketPairs[j].endsWith("-" + symbols[i]) || marketPairs[j].startsWith(symbols[i] + "-")

var symbols = ["ETH", "BTC", "USD", "USDT"];
var marketPairs = ["AAVE-USD", "AAVE-USDT", "AAVE-BTC", "AAVE-ETH"];

var marketDict = {};

for (let i = 0; i < symbols.length; i++) {
  marketDict[symbols[i]] = [];
  for (let j = 0; j < marketPairs.length; j++) {
    if (
      marketPairs[j].endsWith("-" + symbols[i]) ||
      marketPairs[j].startsWith(symbols[i] + "-")
    ) {
      marketDict[symbols[i]].push(marketPairs[j]);
    }
  }
}

console.log(marketDict);

Upvotes: 2

Related Questions