jQuery concatenate variables if both have a value? - javascript

I'm really hoping this isn't a duplicate, although certainly possible and I'm just not searching the right terms.
I'm working on my own password strength checker based on flyingcars version.
And I'm trying to work out a way to combine two variables (only if both exist).
Here's what I've got:
var thisVal = $('.password_input').val(),
thisStrength = zxcvbn(thisVal),
thisMeter = $('.password_strength_meter'),
thisLabel = $('.password-text'),
thisSuggestion = $('.password-text-suggest');
thisSuggestion.text(thisStrength.feedback.warning + ". " thisStrength.feedback.suggestions);
If
Would the best way really be to do multiple if statements? Or is there some way of inlining it to the .text() section?
I'm considering extending this further perhaps, by including the time it would take to crack:
thisSuggestion.text(thisStrength.feedback.warning + ". This password could be cracked in: " + thisStrength.crack_times_display['online_no_throttling_10_per_second'] + ". " + thisStrength.feedback.suggestions);
so hopefully multiple if statements can be avoided.

A quick and clean way to do this is to add all of the variables that might contain strings to an array. You can then filter out the blank or falsey values and join the remaining ones with your chosen delimiter.
const a = 'This will be there',
b = '',
c = null,
d = 'So will this';
let result = [a, b, c, d].filter(x => x).join('. ') + '.';
console.log(result);

Related

Parse email by RegExp in JavaScript in one line; make right case insensitive but keep left

From my code:
//yagh ... apparently there's an off-chance email is case sensitive ...
console.log('yooooooooo0 ' + name.substr(name.indexOf('#')+1));
//console.log('yooooooooo1 ' + name.substr(name.indexOf('#')+1).toLowercase());
console.log('yooooooooo1 ' + name.substr(name.indexOf('#')+1).toLowerCase());
console.log('yooooooooo2 ' + name.substr(name.indexOf('#'),0));
console.log('yooooooooo3 ' + name.split('#')[0]);
console.log('yooooooooo4 ' + /[^#]*/.exec(name)[0]);//hmmm mh
console.log('yooooooooo4_2 ' + /[^#]*$/.exec(name)[0]);//hmmm mh
//hm yea okay ya
console.log(name);//nondestructive and
//pff ...
console.log((/[^#]*/.exec(name)[0])+'#'+(/[^#]*$/.exec(name)[0]).toLowerCase);
let tmp = (/[^#]*/.exec(name)[0])+'#'+ (/[^#]*$/.exec(name)[0]).toLowerCase;
console.log(tmp);
console.log((/[^#]*/.exec(name)[0])+'#'+name.substr(name.indexOf('#')+1).toLowerCase());
var pass = $('#pass1').val();
var crypto = window.crypto || window.msCrypto;
if(crypto.subtle)
{
Say the email that comes with is a#b.C. The point is, I just found that email is only case insensitive right of the #. In theory, admins can choose to let that slide, but in practice most won't to prevent confusion (is what I read).
I want:
console.log((/[^#]*/.exec(name)[0])+'#'+(/[^#]*$/.exec(name)[0]).toLowerCase);
I have a working bit that is:
console.log((/[^#]*/.exec(name)[0])+'#'+name.substr(name.indexOf('#')+1).toLowerCase());
The first one gives me:
a#function toLowerCase(){
[native code]
}
And the second:
a#b.c
Which is fine, but the first one is prettier and less readable, which is great since no one else will be on it, ever.
Is there some way to make the first one work? (Assigning it to let tmp= gives the same reply when log (tmp).
Replace
console.log((/[^#]*/.exec(name)[0])+'#'+(/[^#]*$/.exec(name)[0]).toLowerCase);
by
console.log((/[^#]*/.exec(name)[0])+'#'+(/[^#]*$/.exec(name)[0]).toLowerCase());
You could also do this
const email = 'some.name#some_domain.com'
const [name, domain] = email.split('#')
console.log(`${name}#${domain}`);

Look for substring in a string with at most one different character-javascript

I am new in programing and right now I am working on one program. Program need to find the substring in a string and return the index where the chain starts to be the same. I know that for that I can use "indexOf". Is not so easy. I want to find out substrings with at moste one different char.
I was thinking about regular expresion... but not really know how to use it because I need to use regular expresion for every element of the string. Here some code wich propably will clarify what I want to do:
var A= "abbab";
var B= "ba";
var tb=[];
console.log(A.indexOf(B));
for (var i=0;i<B.length; i++){
var D=B.replace(B[i],"[a-z]");
tb.push(A.indexOf(D));
}
console.log(tb);
I know that the substring B and string A are the lowercase letters. Will be nice to get any advice how to make it using regular expresions. Thx
Simple Input:
A B
1) abbab ba
2) hello world
3) banana nan
Expected Output:
1) 1 2
2) No Match!
3) 0 2
While probably theoretically possible, I think it would very complicated to try this kind of search while attempting to incorporate all possible search query options in one long complex regular expression. I think a better approach is to use JavaScript to dynamically create various simpler options and then search with each separately.
The following code sequentially replaces each character in the initial query string with a regular expression wild card (i.e. a period, '.') and then searches the target string with that. For example, if the initial query string is 'nan', it will search with '.an', 'n.n' and 'na.'. It will only add the position of the hit to the list of hits if that position has not already been hit on a previous search. i.e. It ensures that the list of hits contains only unique values, even if multiple query variations found a hit at the same location. (This could be implemented even better with ES6 sets, but I couldn't get the Stack Overflow code snippet tool to cooperate with me while trying to use a set, even with the Babel option checked.) Finally, it sorts the hits in ascending order.
Update: The search algorithm has been updated/corrected. Originally, some hits were missed because the exec search for any query variation would only iterate as per the JavaScript default, i.e. after finding a match, it would start the next search at the next character after the end of the previous match, e.g. it would find 'aa' in 'aaaa' at positions 0 and 2. Now it starts the next search at the next character after the start of the previous match, e.g. it now finds 'aa' in 'aaaa' at positions 0, 1 and 2.
const findAllowingOneMismatch = (target, query) => {
const numLetters = query.length;
const queryVariations = [];
for (let variationNum = 0; variationNum < numLetters; variationNum += 1) {
queryVariations.push(query.slice(0, variationNum) + "." + query.slice(variationNum + 1));
};
let hits = [];
queryVariations.forEach(queryVariation => {
const re = new RegExp(queryVariation, "g");
let myArray;
while ((searchResult = re.exec(target)) !== null) {
re.lastIndex = searchResult.index + 1;
const hit = searchResult.index;
// console.log('found a hit with ' + queryVariation + ' at position ' + hit);
if (hits.indexOf(hit) === -1) {
hits.push(searchResult.index);
}
}
});
hits = hits.sort((a,b)=>(a-b));
console.log('Found "' + query + '" in "' + target + '" at positions:', JSON.stringify(hits));
};
[
['abbab', 'ba'],
['hello', 'world'],
['banana', 'nan'],
['abcde abcxe abxxe xbcde', 'abcd'],
['--xx-xxx--x----x-x-xxx--x--x-x-xx-', '----']
].forEach(pair => {findAllowingOneMismatch(pair[0], pair[1])});

Javascript: Storing and Sorting Data with Arrays

I am a beginner and I need help with this programming assignment.
Need to do a prompt. Get 10 names as input from user (string inputs). Put the names into an array and then write it out to the webpage.
My question is how do I save the input in the array, when the prompt has to be displayed over and over again for each name the user enters a name? Also, depending on how many names the user wants to enter, the user has a choice of quitting the prompt by typing in the letter 'q'. I am quite proficient at coding while and for loops, but not so much at coding arrays. Tried to search online but couldn't find an answer.
I would love if somebody could explain how to do it. Thanks!
I suggest the following solution:
// Create new array with 10 default values:
var result = new Array(10).fill('');
// Fill array with names via prompt():
eval(((a, b = ['x => x' + '.' + '\n' + 'so\x6De']) => b + '\x28' + a + '\x29')((a, b) => 'q' == (x[b] = prompt())))(result);
// Print result:
console.log(result);
How about something like this?
in your html somewhere
<div id="names">
</div>
function getNames(num) {
var arr = [],
person,
max = num || 5; // number of names you want
return (function R() {
if (arr.length < max) {
person = prompt("Please enter your name");
arr.push(person)
R()
} else {
document.getElementById("names").innerHTML =
"Hello " + arr.join(", ") + "! How are you today?";
}
}())
}
getNames(4)

Replace array-mapped variables with the actual variable name/string?

I am trying to edit a Greasemonkey/jQuery script. I can't post the link here.
The code is obfuscated and compressed with minify.
It starts like this:
var _0x21e9 = ["\x67\x65\x74\x4D\x6F\x6E\x74\x68", "\x67\x65\x74\x55\x54\x43\x44\x61\x74\x65", ...
After "decoding" it, I got this:
var _0x21e9=["getMonth","getUTCDate","getFullYear", ...
It is a huge list (500+ ). Then, it has some variables like this:
month = date[_0x21e9[0]](), day = date[_0x21e9[1]](), ...
_0x21e9[0] is getMonth, _0x21e9[1] is getUTCDate, etc.
Is it possible to replace the square brackets with the actual variable name? How?
I have little knowledge in javascript/jQuery and can not "read" the code the way it is right now.
I just want to use some functions from this huge script and remove the others I do not need.
Update: I tried using jsbeautifier.org as suggested here and in the duplicated question but nothing changed, except the "indent".
It did not replace the array variables with the decoded names.
For example:
jsbeautifier still gives: month = date[_0x21e9[0]]().
But I need: month = date["getMonth"]().
None of the online deobfuscators seem to do this, How can I?
Is there a way for me to share the code with someone, at least part of it? I read I can not post pastebin, or similar here. I can not post it the full code here.
Here is another part of the code:
$(_0x21e9[8] + vid)[_0x21e9[18]]();
[8] is "." and [18] is "remove". Manually replacing it gives a strange result.
I haven't seen any online deobfuscator that does this yet, but the principle is simple.
Construct a text filter that parses the "key" array and then replaces each instance that that array is referenced, with the appropriate array value.
For example, suppose you have a file, evil.js that looks like this (AFTER you have run it though jsbeautifier.org with the Detect packers and obfuscators? and the Unescape printable chars... options set):
var _0xf17f = ["(", ")", 'div', "createElement", "id", "log", "console"];
var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);
var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);
var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];
window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);
In that case, the "key" variable would be _0xf17f and the "key" array would be ["(", ")", ...].
The filter process would look like this:
Extract the key name using text processing on the js file. Result: _0xf17f
Extract the string src of the key array. Result:
keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
In javascript, we can then use .replace() to parse the rest of the JS src. Like so:
var keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
var restOfSrc = "var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);\n"
+ "var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);\n"
+ "var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];\n"
+ "window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);\n"
;
var keyArray = eval (keyArrayStr);
//-- Note that `_0xf17f` is the key name we already determined.
var keyRegExp = /_0xf17f\s*\[\s*(\d+)\s*\]/g;
var deObsTxt = restOfSrc.replace (keyRegExp, function (matchStr, p1Str) {
return '"' + keyArray[ parseInt(p1Str, 10) ] + '"';
} );
console.log (deObsTxt);
if you run that code, you get:
var _0x41dcx3 = eval("(" + '{id: 3}' + ")");
var _0x41dcx4 = document["createElement"]("div");
var _0x41dcx5 = _0x41dcx3["id"];
window["console"]["log"](_0x41dcx5);
-- which is a bit easier to read/understand.
I've also created an online page that takes JS source and does all 3 remapping steps in a slightly more automated and robust manner. You can see it at:
jsbin.com/hazevo
(Note that that tool expects the source to start with the "key" variable declaration, like your code samples do)
#Brock Adams solution is brilliant, but there is a small bug: it doesn't take into account simple quoted vars.
Example:
var _0xbd34 = ["hello ", '"my" world'];
(function($) {
alert(_0xbd34[0] + _0xbd34[1])
});
If you try to decipher this example, it will result on this:
alert("hello " + ""my" world")
To resolve this, just edit the replacedSrc.replace into #Brock code:
replacedSrc = replacedSrc.replace (nameRegex, function (matchStr, p1Str) {
var quote = keyArry[parseInt (p1Str, 10)].indexOf('"')==-1? '"' : "'";
return quote + keyArry[ parseInt (p1Str, 10) ] + quote;
} );
Here you have a patched version.
for (var i = 0; i < _0x21e9.length; i++) {
var funcName = _0x21e9[i];
_0x21e9[funcName] = funcName;
}
this will add all the function names as keys to the array. allowing you to do
date[_0x21e9["getMonth"]]()

javascript : how can i get array in different ways?

hi i have a little problem with my javascript
can i make the simple way to execute content of array with different character of word?
for example :
var word = new Array();
word [0] = "is";
word [1] = "am";
.
.
.
.
word [100] = "when";
var word should be access with 3 ways,in order to reduce process to execute arrays..
first : " "+ word +" ";
second : " "+ word;
third : word +" ";
-thank you for helping-
I'm not exactly sure what you are chasing (fill me in and I'll update), but I'd like to point out a far better way of filling in that array literal...
var word = [
'is',
'am'
];
You can see the index is calculated automatically, and you are not required to repeat the var name for each member definition.
Update
Maybe you want something you can call and get the next array member each time. This should do it...
function getNextMember(array, startIndex) {
startIndex = startIndex || 0;
return function() {
startIndex++;
return array[startIndex];
};
};
var getNextWord = getNextMember(word);
alert(getNextWord() + ' ' + getNextWord());
See it on jsFiddle.
And of course, if you are feeling naughty, you could add that function to Array's prototype.

Categories

Resources