0
var string = "Let's say the user inputs hello world inputs inputs inputs";

My input to get the whole word is "put".

My expected word is "inputs"

Can anyone share your solution? Thanks in advance

5
  • 4
    Someone surely can, but unless you make some effort yourself, we won't. Commented Nov 21, 2014 at 11:56
  • 3
    What if the input is "I put putty on the computer"? Should the result be ["put", "putty", "computer"]? Commented Nov 21, 2014 at 11:58
  • @MichaelLaszlo that's one brilliantly engineered sentence. Commented Nov 21, 2014 at 11:58
  • Regex, matches collection, \b\w*put\w*\b Commented Nov 21, 2014 at 11:59
  • @AlexK Hmm, that looks suspiciously like an answer, not a comment. Commented Nov 21, 2014 at 12:00

2 Answers 2

2

One way to do what you're asking is to split the input string into tokens, then check each one to see if it contains the desired substring. To eliminate duplicates, store the words in an object and only put a word into the result list if you're seeing it for the first time.

function findUniqueWordsWithSubstring(text, sub) {
    var words = text.split(' '),
        resultHash = {},
        result = [];
    for (var i = 0; i < words.length; ++i) {
        var word = words[i];
        if (word.indexOf(sub) == -1) {
            continue;
        }
        if (resultHash[word] === undefined) {
            resultHash[word] = true;
            result.push(word);
        }
    }
    return result;
}

var input = 'put some putty on the computer output',
    words = findUniqueWordsWithSubstring(input, 'put');
alert(words.join(', '));

Sign up to request clarification or add additional context in comments.

Comments

1

A RegEx and filter to remove duplicates;

var string = "I put putty on the computer. putty, PUT do I"

var uniques = {};
var result = (string.match(/\b\w*put\w*\b/ig) || []).filter(function(item) {
   item = item.toLowerCase();
   return uniques[item] ? false : (uniques[item] = true);
});

document.write( result.join(", ") );

// put, putty, computer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.