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
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(', '));
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
Related
I have a laTeX string like this
let result = "\\frac{x}{2}+\\frac{3}{x}";
I want to find the index of "frac"s in the string and put them in a array then I want to find the first '}' char after "frac" and replace it with "}/" and finally remove "frac" from the string.
I used this block of code but it just work correctly when we have one "frac"
let result = "\\frac{x}{2}+\\frac{3}{x}";
if (result.indexOf("frac") != -1) {
for (let i = 0; i < result.split("frac").length; i++) {
let j = result.indexOf("frac");
let permission = true;
while (permission) {
if (result[j] == "}") {
result = result.replace(result[j], "}/")
permission = false;
}
j++;
}
result = result.replace('frac', '');
}
}
console.log(result)
OUTPUT: \\{x}//{2}+\\{3}{x}
Could anyone help me to improve my code?
Something like this?
frac(.+?)}
is the literal frac followed by a capture group that will capture one or more of anything .+ until a } and replace it with that anything plus a }/
Using the function replacement to grab index and replace
let result = "\\frac{x}{2}+\\frac{3}{x}";
let pos = [];
const newRes = result.replace(/frac(.+?)}/g,function(match, found, offset,string) {
console.log(match,found,offset,string)
pos.push(offset)
return `${found}/`; // return the found string with the added slash
})
console.log(pos)
console.log(newRes)
Older answer using two sets of code
let result = "\\frac{x}{2}+\\frac{3}{x}";
let re = /frac/gi, res, pos = [];
while ((res = re.exec(result))) {
pos.push(res.index);
}
const newRes = result.replace(/frac(.+?)}/g,"$1}/")
console.log(pos)
console.log(newRes)
I'm trying to match some words in a string. But I don't have a predefined number of words I need to find.
For example I search for Ubuntu 18 10 in ubuntu-18.10-desktop-amd64.iso.torrent would return true.
Or I could search for centos 7 in CentOS-7-x86_64-LiveGNOME-1804.torrent would also return true.
I don't need to check if it's lowercase or not.
What I tried :
$.get('interdit', function(data) {
var lines = data.split("\n");
$.each(lines, function(n, data_interdit) {
var url_check = $('textarea#url').val()
var split_forbidden = data_interdit.split(/[\s|,|_|.|-|:]+/);
var exist = 0;
$.each(split_forbidden, function(n, data) {
var n = url_check.search("^("+ data +")");
if(n != -1){
exist = 1
}else{
exist = 0
}
console.log('Forbidden: '+ data + ' Result: ' + n);
})
if(exist == 1){
console.log('found')
}
});
});
Sample data of the file interdit :
CentOS.7
Ubuntu-18
You want to look for existing words within the input string without the order being taken into account. You need to use positive lookaheads for this:
var search = 'Ubuntu 18 10';
var str = 'ubuntu-18.10-desktop-amd64.iso.torrent';
var re = new RegExp('^(?=.*' + search.split(/[\s,_.:-]+/).join(')(?=.*') + ')', 'i')
console.log(re.test(str));
This produces a regex as the following (with i flag set):
^(?=.*Ubuntu)(?=.*18)(?=.*10)
RegEx Array
Update
"The code give me an error jsbin.com/pecoleweyi/2/edit?js,console"
Although the question did not include unlikely input such as: *centos 7*, add the following line to escape the special characters that occur in input:
var esc = word.replace(/[.*+?^${}()|[\]\\]/gi, '\\$&');
and change the next line:
var sub = esc.replace(/\s/gi, '.');
The demo below will:
accept a string (str) to search and an array of strings (tgt) to find within the string,
.map() the array (tgt) which will run a function on each string (word)
escape any special characters:
var esc = word.replace(/[.*+?^${}()|[\]\\]/gi, '\\$&');
replace any spaces (/\s/g) with a dot (.):
var sub = esc.replace(/\s/g, '.');
then makes a RegExp() Object so a variable can be inserted in the pattern via template literal interpolation (say that ten times fast):
var rgx = new RegExp(`${sub}`, `gim`);
uses .test() to get a boolean: found = true / not found = false
var bool = rgx.test(str);
create an Object to assign the search string: word as a property and the boolean: bool as it's value.
var obj = {
[word]: bool
};
returns an array of objects:
[{"centos 7":true},{"Ubuntu 18 10":true}]
Demo
var str = `ubuntu-18.10-desktop-amd64.iso.torrent
CentOS-7-x86_64-LiveGNOME-1804.torrent`;
var tgt = [`centos 7`, `Ubuntu 18 10`, `corn flakes`, `gnome`, `Red Hat`, `*centos 7*`];
function rgxArray(str, tgt) {
var res = tgt.map(function(word) {
var esc = word.replace(/[.*+?^${}()|[\]\\]/gi, '\\$&');
var sub = esc.replace(/\s/gi, '.');
var rgx = new RegExp(`${sub}`, `gi`);
var bool = rgx.test(str);
var obj = {
[word]: bool
};
return obj;
});
return res;
}
console.log(JSON.stringify(rgxArray(str, tgt)));
user_input = "";
answer = "";
Array.greeting = ["hi", "hello"]
Array.names = ["john","james"]
user_input = document.getElementById('user_input').value.toLowerCase();
document.getElementById('text_input').innerHTML = user_input;
documnet.getElementById('say_something').innerHTML = say;
if(""){}
else{}
if(Array.greeting.includes(user_input) > 0){
say = "Hello";
}
if(Array.names.includes(user_input) > 0){
say = "User";
}
This is what i understand and have got up and running with correct outputs but how could i use input "hi john" and get output of "Hello User" with out baking it into an array?
You could do it like this:
var greetings = ["hi", "hello"];
var names = ["john","james"];
submit.onclick = function () {
// Split input into words, and convert that array to a Set for fast lookup
var words = new Set(user_input.value.split(/\s+/));
// Choose a greeting that is not among the input words.
// If all of them occur in the input, take the first greeting word
var greeting = greetings.find( greeting => !words.has(greeting)) || greetings[0];
// Choose a name that is not among the input words (or take the first)
var name = names.find( name => !words.has(name)) || names[0];
// Output with textContent (not innerHTML!)
text_input.textContent = user_input.value;
say_something.textContent = greeting + ' ' + name;
}
Input: <input id="user_input"><button id="submit">Submit</button><br>
You said: <span id="text_input"></span><br>
Reply: <span id="say_something"></span>
Obviously, when you enter both "hi" and "hello", the code will not find a greeting to use. In that case it uses the first greeting in the array ("hi"). The same principle applies for the names.
Let's simplify your requirement as:
You want to check if any element of an array "arr" contains part of string "s".
var check = function(arr, s) {
for (var i = 0; i < arr.length; i++) {
if (s.indexOf(arr[i]) > -1) {
return true;
}
}
return false;
}
Lets consider i have a string & want to extract uncommon keywords for SEO. $text = "This is some text. This is some text. Vending Machines are great.";
& Will define a array of common words to ignore keywords in extracted list like $commonWords = ['i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','www'];
Expected output: Result=[some,text,machines,vending]
Would really appreciate if Could any one help us to write generic logic or procedure for the extracting keywords from string?
This can help ( it supports multi languages):
https://github.com/michaeldelorenzo/keyword-extractor
var sentence = "President Obama woke up Monday facing a Congressional defeat that many in both parties believed could hobble his presidency."
// Extract the keywords
var extraction_result = keyword_extractor.extract(sentence,{
language:"english",
remove_digits: true,
return_changed_case:true,
remove_duplicates: false
});
Some like this
var $commonWords = ['i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','www'];
var $text = "This is some text. This is some text. Vending Machines are great.";
// Convert to lowercase
$text = $text.toLowerCase();
// replace unnesessary chars. leave only chars, numbers and space
$text = $text.replace(/[^\w\d ]/g, '');
var result = $text.split(' ');
// remove $commonWords
result = result.filter(function (word) {
return $commonWords.indexOf(word) === -1;
});
// Unique words
result = result.unique();
console.log(result);
var string = "This is some text. This is some text. Vending Machines are great.";
var substrings = ['your','words', 'here'],
var results = array();
for (var i = substrings.length - 1; i >= 0; --i) {
if (string.indexOf(substrings[i]) != -1) {
// str contains substrings[i]
array.push(substrings[i]);
}
}
var arrayLength = commonWords.length;
var words = []; //new array to say the words
for (var i = 0; i < arrayLength; i++) {
if ($text.indexOf(commonWords[i]) > -1){
words.push(commonWords[i]);
}
}
What are some clean ways to print out last characters of all words in a string. For example, a phrase like "laugh ride lol hall bozo " --> "hello" and "dog polo boo sudd noob smiley ride " --> goodbye.
These lines would return "1" and undefined. Any help is much appreciated.
var decrypt = function (message) {
var solution = [];
for (var i = 0; i < message.length; i++) {
if(message.charAt(i)===" ") {
return solution.push(message.charAt(i-1));
};
};
};
var resulta = decrypt("laugh ride lol hall bozo ")
console.log(resulta); // logs "hello"
var resultb = decrypt("dog polo boo sudd noob smiley ride ")
console.log(resultb); // logs "goodbye"
Don't return inside the loop, just append the charater to the result. When the loop is done, return what you want. Since you apparently want to return a string, you don't need an array.
var decrypt = function (message) {
var solution = '';
for (var i = 0; i < message.length; i++) {
if(message.charAt(i)===" ") {
solution += message.charAt(i-1);
};
};
return solution;
};
var resulta = decrypt("laugh ride lol hall bozo ")
console.log(resulta); // logs "hello"
var resultb = decrypt("dog polo boo sudd noob smiley ride ")
console.log(resultb); // logs "goodbye"
Assuming the words are separated by spaces you can do it in one line:
var decrypt = function (message) {
return (message+" ").match(/\w\s/g).join("").replace(/\s/g,"");
}
The regex /\w\s/g will match a word character followed by a space. The .match() method will return an array of all such matches. .join() will join the array elements into a string. And then .replace() will remove the spaces from that string.
Note that I'm using (message+" ") to add an extra space to the input string just in case it doesn't already have one at the end.
Also the code I showed doesn't allow for strings that don't have any "word characters" in them. If you want to test for that you need two lines:
var decrypt = function (message) {
var m = (message+" ").match(/\w\s/g);
return m ? m.join("").replace(/\s/g,"") : "";
//include default value for non match here^^
}
Another clean solution is
var decrypt = function (message) {
return message.split(' ')
.map(function(word) { return word.slice(-1); })
.join('');
}
This is relies on Array.prototype.map, which was added in ES5 with support for all modern browsers (http://kangax.github.io/compat-table/es5/#Array.prototype.map).
Considering you only care about the last character of each word, I would loop through the string in reverse. This allows you to also print the last character in the string without appending a space on the end of the encoded message.
function decrypt(message) {
var c, secret = '', lastSpace = true;
for (var i = (message || '').length - 1; i >= 0; i--, lastSpace = c === ' ') {
c = message.charAt(i);
if (lastSpace) secret = c + secret;
}
return secret;
}