Hello, I'm trying to make a simple matching game in javascript.
If the the user inserts the text president goes crazy in any way that contains every strings in word_tmp, then the word_tmp becomes true, and if he misses one string then it becomes false.
word_tmp = ['president', 'goes', 'crazy'];
// string 1 contains the president, goes and crazy at one string
string1 = 'president goes very crazy'; // should output true
// string 2 doesn't contain president so its false.
string2 = 'other people goes crazy'; // should output false
How can I accomplish this?
Try this:
var word_tmp = ['president', 'goes', 'crazy'];
var string1 = 'president goes very crazy';
var isMatch = true;
for(var i = 0; i < word_tmp.length; i++){
if (string1.indexOf(word_tmp[i]) == -1){
isMatch = false;
break;
}
}
return isMatch //will be true in this case
You can do it with simple reduce call:
word_tmp.reduce(function(res, pattern) {
return res && string1.indexOf(pattern) > -1;
}, true);
The same code, wrapped in a function:
var match_all = function(str, arr) {
return arr.reduce(function(res, pattern) {
return res && str.indexOf(pattern) > -1;
}, true);
};
match_all(string1, word_tmp); // true
match_all(string2, word_tmp); // false
But this solution won't work for you if you want to match whole words. I mean, it will accept strings like presidential elections goes crazy, because president is a part of the word presidential. If you want to eliminate such strings as well, you should split your original string first:
var match_all = function(str, arr) {
var parts = str.split(/\s/); // split on whitespaces
return arr.reduce(function(res, pattern) {
return res && parts.indexOf(pattern) > -1;
}, true);
};
match_all('presidential elections goes crazy', word_tmp); // false
In my example I'm splitting original string on whitespaces /\s/. If you allow punctuation marks then it's better to split on non-word characters /\W/.
var word_tmp = ['president', 'goes', 'crazy'];
var str = "president goes very crazy"
var origninaldata = str.split(" ")
var isMatch = false;
for(var i=0;i<word_tmp.length;i++) {
for(var j=0;j<origninaldata.length;j++) {
if(word_tmp[i]==origninaldata[j])
isMatch = true;
}
}
Related
I am trying to use Regex to test if a certain string contains only sets of four non-duplicate characters.
For example I would like to test string
acbdbcaddacb
which would return true as it can return
acbd
bcad
dacb
i.e. sets of four characters which have no duplicates even though the entire string does.
I have tried the following regex which does not work for example and I am not sure why:
/^(?:(?:([a-d])(?!.{0,2}\1))(?:([a-d])(?!.{0,1}\1))(?:([a-d])(?!\1))[a-d])+$/
Any solutions?
Thank you
You're close. Your current regex is only checking if the 2nd - 4th letters in each group match the 1st. I believe /^(?:(?:([a-d])(?!.{0,2}\1))(?:([a-d])(?!.{0,1}\1|\2))(?:([a-d])(?!\1|\2|\3))[a-d])+$/ should work... or at least it's getting closer to correct I'm not sure if I left out some edge cases but it seems to be working for my test strings
Try this :
function check(str) {
var len = str.length; // check string length
if (len % 4 == 0) { // pass if divided by 4 == true
var arr = str.match(/.{4}/g); // make the in array
var res = [];
for (i = 0; i < arr.length; i++) {
if (arr[i].match(/^(?:([a-zA-Z])(?!.*\1))*$/)) {
res.push(arr[i]); // push if passed regex
}
}
if (arr.length === res.length) { // if they same that means true
console.log("true");
} else {
console.log("false");
}
} else {
console.log("false");
}
}
var str1 = "acbdbcaddacb";
check(str1); // true
var str2 = "aabbccdd";
check(str2); // false
var str3 = "abcde";
check(str3); // false
var str4 = "abcdabcdabcdabcd";
check(str4); // true
var str5 = "abcdabcdabcdabc4";
check(str5); // false
I am trying to compare two strings to see if ALL of one of the string's input is also within another string, regardless of order.
So far I have the following code...
What am I doing wrong?
var str1= "rkqodlw"
var str2= "world"
StringScrambler(str1, str2);
function StringScrambler(str1, str2) {
var string1= str1.split("").sort();
console.log(string1);
var string2 = str2.split("").sort();
console.log(string2);
matches = [];
for (i=0; i< string1.length; i++) {
for (j=0; j<string2.length; i++) {
while (j === i) {
matches.push(j);
console.log(matches);
var matchSort = matches.sort();
console.log(matchSort);
if (matchSort === string2) {
return true;
}else {
return false;
}
}
}
}
}
All the answers this far work fine but they will not work for words with double letters in the second string but not in the first (for eg. 'worlld' - notice the double L). The trick is to affect the first word such that it removes the found character(s) so that the same letter is not checked again. Something like this would do the trick:
// Check if the second string's characters are
// found in the first string
function StringScrambler(str1, str2) {
var arr1 = str1.split(''),
arr2 = str2.split(''),
isATrueSubset = true,
indexOfChar;
arr2.forEach(function(char) {
indexOfChar = arr1.indexOf(char);
if (indexOfChar > -1) {
// Remove the character that was found
// to avoid matching against it again
arr1.splice(indexOfChar, 1);
} else {
isATrueSubset = false;
// No need to continue
return;
}
});
console.log(isATrueSubset);
return isATrueSubset;
}
StringScrambler('rkqodlw ', 'world '); // outputs true
StringScrambler('rkqodlw ', 'worlld '); // outputs false
var one = "dlrow";
var two = "world";
var allCharsFound = true;
one.split("").map(function(char) {
if (two.indexOf(char) < 0) {
allCharsFound = false;
}
});
console.log(allCharsFound);
var str1= "rkqodlw";
var str2= "world";
function test($str1, $str2) {
var string2 = str2.split("");
for(var i=0; i<string2.length; i++) {
if (str1.indexOf(string2[i]) == -1) {
return false;
}
}
return true;
}
You can use the following code to do this task:
alert (AllFirstInSecond("world", "rkqodlw"));
alert (AllFirstInSecond("worldz", "rkqodlw"));
function AllFirstInSecond(str1, str2) {
var pos = str1.length - 1;
while (pos >= 0) {
if (str2.indexOf(str1.substr(pos--,1)) == -1) {
return false;
}
}
return true;
}
It simply checks every single character in the first string to see if it's in the second. If not, it returns false.
Only once all have been found does it return true.
There are possibilities for optimisation (every character is checked even if it's a duplicate that's already been checked) but, unless your strings are particularly large, there's probably not much absolute gain to be had.
If str2 is always a subset of str1, then this answer can be used
Compute intersection of two arrays in JavaScript
var arr1 = "rkqodlw".split("");
var arr2 = "world".split("");
var commonValues = arr2.filter(function(value) {
return arr1.indexOf(value) > -1;
});
alert(commonValues.join(""))
This will compare each words of the second string in the first one and if its present it will be added in the mathes array.
var str1= "rkqodlw";
var str2= "world2";
StringScrambler(str1, str2);
function StringScrambler(str1, str2) {
var string2 = str2.split("").sort();
console.log(string2);
matches = [];
for (j=0; j<string2.length; j++) {
if(str1.indexOf(string2[j]) > -1){
matches.push(string2[j]);
console.log(string2[j]);
}
}
console.log(matches);
}
try this:
var str1= "rkqodlw"
var str2= "world"
StringScrambler(str1, str2);
function StringScrambler(str1, str2) {
var string1 = str1.split("").sort();
var string2 = str2.split("").sort();
matches = [];
for (i = 0; i < string1.length; i++) {
if (string2.indexOf(string1[i]) > -1) matches.push(string1[i]);
}
return matches
}
I have a tokenised string like so;
var route = a/b/{firstId}/c/d/{nextId}
and I am wondering if it is possible with regex to get the value of "firstId" via a second string with tokens already replaced.
Example, if I have a given string;
var partPath = a/b/33
I can do something like;
function getValueFromPath(path, route){
//regex stuff
return tokenValue; //Expected result 33
}
getValueFromPath(partPath, route);
Thank you,
C.
A regex solution would be overly complicated (if you didn't define the route with a regexp right away). I'd just use
function getValueFromPath(path, route){
var actualParts = path.split("/"),
expectedParts = route.split("/"),
result = {};
for (var i=0; i<expectedParts.length; i++) {
if (i >= actualParts.length)
return result;
var actual = actualParts[i],
expected = expectedParts[i];
if (/^\{.+\}$/.test(expected))
result[ expected.slice(1, -1) ] = actual;
else if (actual != expected)
// non-matching literals found, abort
return result;
}
return result;
}
> getValueFromPath("a/b/33", "a/b/{firstId}/c/d/{nextId}")
{firstId: "33"}
> getValueFromPath("a/b/33/c/d/42/x", "a/b/{firstId}/c/d/{nextId}")
{firstId: "33", nextId: "42"}
Here's the same thing with "regex stuff" (notice that regex special characters in the route are not escaped, you have to take care about that yourself):
function getValueFromPath(path, route){
var keys = [];
route = "^"+route.split("/").reduceRight(function(m, part) {
return part + "(?:/" + m + ")?"; // make right parts optional
}).replace(/\{([^\/{}]+)\}/g, function(m, k) {
keys.push(k); // for every "variable"
return "([^/]+)"; // create a capturing group
});
var regex = new RegExp(route); // build an ugly regex:
// regex == /^a(?:\/b(?:\/([^/]+)(?:\/c(?:\/d(?:\/([^/]+))?)?)?)?)?/
var m = path.match(regex),
result = {};
for (var i=0; m && i<keys.length; i++)
result[keys[i]] = m[i+1];
return result;
}
You can create a regexp like this:
function getValueFromPath(path, route){
tokenValue = path.match(route)[1];
return tokenValue; //Expected result 33
}
var route = /\/a\/b\/([^\/]+)(\/c\/d\/([^\/]+))?/;
var partPath = '/a/b/33';
getValueFromPath(partPath, route); // == 33
http://jsfiddle.net/firstclown/YYvvn/2/
This will let you extract the first value at the first match with [1] and you can get the nextId by changing that to [3] (since [2] will give you the whole path after the 33).
Let's sat I have the sentence "I like cookies" and the sentence "I_like_chocolate_cookies".
How do I split the string "I like cookies" and check if the words exists in the second sentence?
Like this
var words = "I like cookies".replace(/\W/g, '|');
var sentence = "I_like_chocolate_cookies";
console.log(new RegExp(words).test(sentence));
https://tinker.io/447b7/1
Here's some sample code:
str1 = 'I like cookies'
str2 = 'I_like_chocolate_cookies'
// We convert the strings to lowercase to do a case-insensitive check. If we
// should be case sensitive, remove the toLowerCase().
str1Split = str1.toLowerCase().split(' ')
str2Lower = str2.toLowerCase()
for (var i = 0; i < str1Split.length; i++) {
if (str2Lower.indexOf(str1Split[i]) > -1) {
// word exists in second sentence
}
else {
// word doesn't exist
}
}
Hope this helps!
like this?
var x ="i like grape";
var c ="i_don't_like";
var xaar = x.split(' ');
for(i=0;i<xaar.length;i++){
if(c.indexOf(xaar[i])>-1) console.log(xaar[i]);
}
var foo = "I_like_chocolate_cookies";
var bar = "I like chocolate cookies";
foo.split('_').filter(function(elements) {
var duplicates = []
if(bar.split().indexOf(element) != -1) {
return true;
}
});
How can I test if a RegEx matches a string exactly?
var r = /a/;
r.test("a"); // returns true
r.test("ba"); // returns true
testExact(r, "ba"); // should return false
testExact(r, "a"); // should return true
Either modify the pattern beforehand so that it only matches the entire string:
var r = /^a$/
or check afterward whether the pattern matched the whole string:
function matchExact(r, str) {
var match = str.match(r);
return match && str === match[0];
}
Write your regex differently:
var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false
If you do not use any placeholders (as the "exactly" seems to imply), how about string comparison instead?
If you do use placeholders, ^ and $ match the beginning and the end of a string, respectively.
In case anyone receives an error like
Syntax Error: Invalid regular expression
by using the .match() function. You could always go back to the roots:
!!note this code is for matchin an exact string, if you want to search for an exact phrase in a string, you should filter it before hand
console.log("Exact data found: ", hasExactString("?hello", "?hello"))
console.log("Exact data found: ", hasExactString("?hello", "?helloBye"))
function hasExactString(data, searchTerm) {
console.log("search for ", searchTerm, " in ", data);
data = data.toLowerCase(); //if search term should be case insensitive
const searchExpressionLength = searchTerm.length;
const dataInputLength = data.length;
if (dataInputLength != searchExpressionLength) {
return false;
}
else {
//search letter by letter -back to the roots
for (var i = 0; i < searchExpressionLength; i++) {
if (data[i] != searchTerm[i]) {
return false;
}
}
return true;
}
}
...13 years late, but nonetheless^^
var data = {"values": [
{"name":0,"value":0.12791263050161572},
{"name":1,"value":0.13158780927382124}
]};
//JSON to string conversion
var a = JSON.stringify(data);
// replace all name with "x"- global matching
var t = a.replace(/name/g,"x");
// replace exactly the value rather than all values
var d = t.replace(/"value"/g, '"y"');
// String to JSON conversion
var data = JSON.parse(d);
Here's what is (IMO) by far the best solution in one line, per modern javascript standards:
const str1 = 'abc';
const str2 = 'abc';
return (str1 === str2); // true
const str1 = 'abcd';
const str2 = 'abc';
return (str1 === str2); // false
const str1 = 'abc';
const str2 = 'abcd';
return (str1 === str2); // false