Home > Software engineering >  Check if the word in the sentence is also in the array
Check if the word in the sentence is also in the array

Time:05-10

If the word in the sentence is also in the array, take the first 3 letters of this word and put a period at the end.

var arr = ['select', 'delete', 'Truncate', 'insert', 'update']

function checkValue(value, arr) {
  var newText;

  for (var i = 0; i < arr.length; i  ) {
    var name = arr[i];
    if (value.toLowerCase().includes(name.toLowerCase())) {
      newText = value.toLowerCase().replace(name, name.substring(0, 3));
      break;
    }
  }
  return newText;
}


console.log(checkValue('Hello Hello Delete33 Hello', arr));

Its giving me : hello hello del33 hello.

But I want : Hello Hello Del. Hello.

CodePudding user response:

You can create a regex matching your arr items after a word boundary and consuming any word chars after them, and replace with the first three chars appending a dot right after:

var arr = ['select', 'delete', 'Truncate', 'insert', 'update']
var re = new RegExp("\\b(?:"   arr.join('|')   ")\\w*", 'ig')

function checkValue(value, re) {
  return value.replace(re, (x) => x.substr(0,3)   ".");
}

console.log(checkValue('Hello Hello Delete33 Hello', re));
// => Hello Hello Del. Hello

See the regex demo. Details:

  • \b - a word boundary
  • (?:select|delete|Truncate|insert|update) - a non-capturing group matching one of the words
  • \w* - zero or more word chars (letters, digits, _).

CodePudding user response:

var arr = ['select', 'delete', 'truncate', 'insert', 'update']

function checkValue(value, arr) {
  return value.split(" ").map(x => arr.find(y => x.toLowerCase().includes(y)) ? x.substring(0, 3)   "." : x).join(" ");
}


console.log(checkValue('Hello Hello Delete33 Hello', arr));

CodePudding user response:

The key thing is that you're getting the substring but retaining the numbers, and not adding a full-stop.

Here's an alternative method using map, some, and join.

const arr = ['select', 'delete', 'Truncate', 'insert', 'update'];

function checkValue(value, arr) {

  // `split` the string into words, and `map`
  // over them
  return value.split(' ').map(word => {

    // If one of the lowercase words in the array
    // is included included in the lowercase word...
    const found = arr.some(el => {
      return word
        .toLowerCase()
        .includes(el.toLowerCase());
    });

    // ...return the updated word
    if (found) return `${word.slice(0, 3)}.`;

    // Otherwise just return the word
    return word;

  // And `join` the array back to a string
  }).join(' ');

}

const str = 'Hello Hello Delete33 Hello Truncate';
const out = checkValue(str, arr);
console.log(out);

Additional documentation

  • Related