Peter Abraham
Peter Abraham

Reputation: 81

Get Full string using part of a given string

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

Upvotes: 0

Views: 80

Answers (2)

Alex K.
Alex K.

Reputation: 175976

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

Upvotes: 1

Michael Laszlo
Michael Laszlo

Reputation: 12239

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(', '));

Upvotes: 2

Related Questions