javascript : how can i get array in different ways? - javascript

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.

Related

jquery put comma between every variable except last

I have a script that will insert the checked checboxes and radios in the value() of an input tag.
var burgernavn = meat + " with " + bread + " and " + onion + tomato + cheese + salad;
$('#burger-navn').val(burgernavn);
Onion, tomato, cheese and salad needs to have1 " ," between them, except the last two who need " and " between them.
Thats the first thing.
Second thing is that these variables represent checkboxes, so they can be undefined, in which case they should not be put into $('#burger-navn').val(). They can all be undefined, in which case no commas or "and" should be put in.
I hope this is accomplishable.
Capture all checked values in an array (this makes sure that whatever values in this array, all are defined). Also, it will give you count of values that you need to pass to input box.
var checkedValues = document.getElementsByClassName('checkbox');
Iterate over this array, check for last values. (Check my comments in below code snippet)
var commaValues = "", otherValues= "";
//we are iterating only until (total values -2)
for(var i = 0; i < checkedValues.length - 2 ; i++){
//append comma with each value
commaValues += checkedValues[i].concat(",");
}
//append 'And' for last two values if total valuesa re more than one
if(checkedValues.length > 1){
otherValues = checkedValues[checkedValues.length-1].concat("and", checkedValues[checkedValues.length])
}
else if(checkedValues.length == 1){
otherValues = checkedValues[0];
}
//finally concat both strings and put this concated string in input
$('#burger-navn').val(otherValues.concat(commaValues));
So, I hope you got the idea. This code snippet might need a bit tweak since I didn't had your html code and sample data, but it is easily doable using this snippet as reference. Cheers
You can do this pretty easy with jQuery $.map.
var checkboxes = $('input:checkbox');
var commaString = $.map($('input:checkbox'), function( ele, i ) {
return $(ele).val() + (i + 2 == checkboxes.length ? " and" : (i + 1 != checkboxes.length) ? ",": "");
}).join(" ");

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])});

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"]]()

.replace method in JavaScript and duplicated characters

I'm trying to use JavaScript to insert HTML ruby characters on my text. The idea is to find the kanji and replace it with the ruby character that is stored on the fgana array. My code goes like this:
for (var i = 0; i < kanji.length; i++) {
phrase = phrase.replace(kanji[i],"<ruby><rb>" + kanji[i] + "</rb><rt>" + fgana[i] + "</rt></ruby>");
}
It does that just fine when there aren't duplicated characters to be replaced, but when there are the result is different from what I except. For example, if the arrays are like this:
kanji = ["毎朝","時","時"]
fgana = ["まいあさ"、"とき"、"じ"]
And the phrase is あの時毎朝6時におきていた the result becomes:
あの<ruby><rb><ruby><rb>時</rb><rt>じ</rt></ruby></rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 時 におきていた。
Instead of the desired:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt> におきていた。
To illustrate it better, look at the rendered example:
Look at how the first 時 receives both values とき and じ while the second receives nothing. The idea is to the first be とき and the second じ (as Japanese has different readings for the same character depending on some factors).
Whats might be the failure on my code?
Thanks in advance
It fails because the char you are looking for still exists in the replaced version:
...replace(kanji[i],"<ruby><rb>" + kanji[i]...
And this one should work:
var kanji = ["毎朝", "時", "時"],
fgana = ["まいあさ", "とき", "じ"],
phrase = "あの時毎朝 6 時におきていた",
rx = new RegExp("(" + kanji.join("|") + ")", "g");
console.log(phrase.replace(rx, function (m) {
var pos = kanji.indexOf(m),
k = kanji[pos],
f = fgana[pos];
delete kanji[pos];
delete fgana[pos];
return "<ruby><rb>" + k + "</rb><rt>" + f + "</rt></ruby>"
}));
Just copy and paste into console and you get:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb><rt>じ</rt></ruby>におきていた
Above line is a bit different from your desired result thou, just not sure if you indeed want this:
...6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt>...
^^^^^ here ^ not here?

Javascript splitting string using only last splitting parameter

An example of what im trying to get:
String1 - 'string.co.uk' - would return 'string' and 'co.uk'
String2 - 'random.words.string.co.uk' - would return 'string` and 'co.uk'
I currently have this:
var split= [];
var tld_part = domain_name.split(".");
var sld_parts = domain_name.split(".")[0];
tld_part = tld_part.slice(1, tld_part.length);
split.push(sld_parts);
split.push(tld_part.join("."));
With my current code, it takes the split parameter from the beginning, i want to reverse it if possible. With my current code it does this:
String1 - 'string.co.uk' - returns 'string' and 'co.uk'
String2 - 'random.words.string.co.uk' - would return 'random` and 'words.string.co.uk'
Any suggestions?
To expand upon elclanrs comment:
function getParts(str) {
var temp = str.split('.').slice(-3) // grabs the last 3 elements
return {
tld_parts : [temp[1],temp[2]].join("."),
sld_parts : temp[0]
}
}
getParts("foo.bar.baz.co.uk") would return { tld_parts : "co.uk", sld_parts : "baz" }
and
getParts("i.got.99.terms.but.a.bit.aint.one.co.uk") would return { tld_parts : "co.uk", sld_parts : "one" }
try this
var str='string.co.uk'//or 'random.words.string.co.uk'
var part = str.split('.');
var result = part[part.length - 1].toString() + '.' + part[part.length - 1].toString();
alert(result);
One way that comes to mind is the following
var tld_part = domain_name.split(".");
var name = tld_part[tld_part.length - 2];
var tld = tld_part[tld_part.length - 1] +"."+ tld_part[tld_part.length];
Depending on your use case, peforming direct splits might not be a good idea — for example, how would the above code handle .com or even just localhost? In this respect I would go down the RegExp route:
function stripSubdomains( str ){
var regs; return (regs = /([^.]+)(\.co)?(\.[^.]+)$/i.exec( str ))
? regs[1] + (regs[2]||'') + regs[3]
: str
;
};
Before the Regular Expression Police attack reprimand me for not being specific enough, a disclaimer:
The above can be tightened as a check against domain names by rather than checking for ^., to check for the specific characters allowed in a domain at that point. However, my own personal perspective on matters like these is to be more open at the point of capture, and be tougher from a filtering point at a later date... This allows you to keep an eye on what people might be trying, because you can never be 100% certain your validation isn't blocking valid requests — unless you have an army of user testers at your disposal. At the end of the day, it all depends on where this code is being used, so the above is an illustrated example only.

Categories

Resources