How to rearrange characters javascript - javascript

Found some things like in Visual Basic but not Javascript and exactly what I'm trying to do. It's a tad bit different. I'm trying to figured out how to rearrange characters in a string, it's in a for loop as well in order to cut the string in half. Now I need to rearrange that.
First I have:
12345678910111213141516
then in the for loop
12345678
I'm trying fix it so now I get
72648531
But I have to do it in a way so people can't read the code and know that there's 8 characters at this point in the string without hard work and trouble. My for loop is also jumbled up and screwy so it can't be figured out. Something like this. I really cannot post the code though.
var con = "";
for (var i = complex math that equals 0; i < complex math to equal 8; i++) {
var newStr = word[i]; // I need it to come out to the rearranged somewhere close by
var con = con+""+newStr;
}

Two commonly used techniques come to mind:
A common approach to things is by doing some XOR calculations: Look at this unrelated examples:
http://www.javascriptsource.com/passwords/xor-encryption4.html
Extracting information from page with Jsoup
You can use tools like http://www.javascriptobfuscator.com/Default.aspx to make it harder for people to figure your code.

Related

String separation and combining

I have a challenge that I am trying to solve and cannot seem to come up with a solid solution.
I have 3 records like this:
"a,b,c,d,e","1,2,3,4,5","record 1"
"f,g,h,i","11,12,15,16","record 2"
"x,y,z","19,20,21","record 3"
Looking to create this output
"a,1"
"b,2"
"c,3"
"d,4"
"e,5"
...
...
"y,20"
"z,21"
How would I go about this using java-script or
I have have worked out how to separate each string but collecting both substrings and looping through seems to be a challenge.
This can get a little bit Tricky if you dont have a constant format.
In this example i have two strings and each sub-string is separated by ",".
Also both strings should be the same length.
I return the result as an array here. You can append it to a existing string instead.
s1 = "1,2,3,4,5";
s2 = "a,b,c,d,e";
s3 = [];
for(i=0; s1.length>i;i++){
if(s1[i] != ","){
s3.push(s1[i]+","+s2[i]);
}
}
console.log(s3);
Since im not sure if i did understand the Question correctly...
If you dont understand something or the answer is not what you excepted, let me know in the comments and i will try to adapt to it.

bigInt to base2

I'd like to get for really big decimal values like e.g. 4.951760157141521e+27 to the matching binaryString using pure javaScript.
I'm aware that 4.951760157141521e+27 not really is a normal integer anymore what also leads to the problem that just using toString(2) does not work anymore.
print = function(i) { console.log(i) }
let myDecimalNumber = 42;
print(+myDecimalNumber.toString(2));
let myDecimalNumberBIG = 4.951760157141521e+27;
print(+myDecimalNumberBIG.toString(2));
How can I fix this? My idea was to use something like a bigInt library but it seems like currently I could not find any working solution so I would really appreciate a working example :)

jQuery Nested Methods

Excuses if this has been posted, not sure how to search for such a thing.
I'm working on a website and I'd like to know what current industry conventions are. I am more concerned if there is a reason to avoid calling a method inside of another method.
Below I've placed a few examples, please let me know which one is best.
First, easy example on two lines:
var formattedRole = HTMLheaderRole.replace("%data%", bio.role);
$("#header").prepend(formattedRole);
What about all on one line?
$("#header").prepend(HTMLheaderRole.replace("%data%", bio.role));
Let's get a little more complicated:
var formattedEmployer = HTMLworkEmployer.replace("%data%", work.jobs[job].employer);
var formattedTitle = HTMLworkTitle.replace("%data%", work.jobs[job].title);
var formattedConcat = formattedEmployer.concat(formattedTitle);
$(".work-entry:last").append(formattedConcat);
How about just condensing one of those lines?
var formattedEmployer = HTMLworkEmployer.replace("%data%", work.jobs[job].employer);
var formattedTitle = HTMLworkTitle.replace("%data%", work.jobs[job].title);
$(".work-entry:last").append(formattedEmployer.concat(formattedTitle));
Thanks tons for the input!
Technically, avoiding the extra variable assignments in both of the first examples is slightly more efficient. However, the amount of resources saved is so trivial that you would have to be running the function thousands of times on a particularly old mobile device to see and difference. That said, readability is king when comparing two segments of code that have nearly identical performance. Choose whichever option is easier for you or some other maintainer to read.

Asymmetrical search for special characters in JavaScript

I'm trying to implement an asymmetrical search for a dictionary web app, so searching for ü, for example, will return only tokens that actually contain ü, but searching for u will return both u and ü. (This is so users who don't know how to type special characters can still search for them, but users who do know how to type them won't be inundated with the plain character forms unnecessarily.)
It has to all be client-side JavaScript without any external libraries.
I've managed to make the second search type work by running both the search term and the text I'm searching through the following function, effectively merging special characters with their plain counterparts:
function cleanUp(dirty) {
cleaned = dirty.replace(/[áàâãäāă]/ig,"a");
cleaned = cleaned.replace(/đ/ig,"d");
cleaned = cleaned.replace(/[éèêẽëēĕ]/ig,"e");
cleaned = cleaned.replace(/[íìîĩïīĭ]/ig,"i");
cleaned = cleaned.replace(/ñ/ig,"n");
cleaned = cleaned.replace(/[óòôõöōŏ]/ig,"o");
cleaned = cleaned.replace(/[úùûũüūŭ]/ig,"u");
return cleaned;
}
I then compare the strings to get my results with something like:
var search_term = cleanup(search_input.value);
var text_to_search = cleanup(main_text);
if (text_to_search.indexOf(search_term) > -1) ... //do something
It's not elegant, but it works. After cleaning up both strings the user can search for i.e. uber and get über even if they don't know how to type ü. But if they do know how, searching for über directly also returns things like uber, which is what I don't want.
I've already thought of things like checking for each special character separately for each search term or duplicating every dictionary entry that has a special character to produce a special-character and a plain-character version, but all of my ideas would seriously slow down the processing time for the search.
Any ideas are greatly appreciated.
The answer you posted sounds quite reasonable.
I would just like to suggest a cleaner way (pun intended) to code your cleanup() function and similar functions that do a series of string operations:
function cleanUp(dirty) {
return dirty
.replace(/[áàâãäāă]/ig,"a")
.replace(/đ/ig,"d")
.replace(/[éèêẽëēĕ]/ig,"e")
.replace(/[íìîĩïīĭ]/ig,"i")
.replace(/ñ/ig,"n")
.replace(/[óòôõöōŏ]/ig,"o")
.replace(/[úùûũüūŭ]/ig,"u");
}
I ended up checking to see if the search term contained any special characters, and if it did, I didn't run it through cleanup(), and compared it to the original dictionary entry instead of the cleaned one. Thanks for the comments everyone.

Javascript - get strings inside a string

var str = '<div part="1">
<div>
...
<p class="so">text</p>
...
</div>
</div><span></span>';
I got a long string stored in var str, I need to extract the the strings inside div part="1". Can you help me please?
you could create a DOM element and set its innerHTML to your string.
Then you can iterate through the childNodes and read the attributes you want ;)
example
var str = "<your><html>";
var node = document.createElement("div");
node.innerHTML = str;
for(var i = 0; i < node.childNodes.length; i++){
console.log(node.childNodes[i].getAttribute("part"));
}
If you're using a library like JQuery, this is trivially easy without having to go through the horrors of parsing HTML with regex.
Simply load the string into a JQuery object; then you'll be able to query it using selectors. It's as simple as this:
var so = $(str).find('.so');
to get the class='so' elememnt.
If you want to get all the text in part='1', then it would be this:
var part1 = $(str).find('[part=1]').text();
Similar results can be achieved with Prototype library, or others. Without any library, you can still do the same thing using the DOM, but it'll be much harder work.
Just to clarify why it's a bad idea to do this sort of thing in regex:
Yes, it can be done. It is possible to scan a block of HTML code with regex and find things within the string.
However, the issue is that HTML is too variable -- it is defined as a non-regular language (bear in mind that the 'reg' in 'regex' is for 'regular').
If you know that your HTML structure is always going to look the same, it's relatively easy. However if it's ever going to be possible that the incoming HTML might contain elements or attributes other than the exact ones you're expecting, suddenly writing the regex becomes extremely difficult, because regex is designed for searching in predictable strings. When you factor in the possibility of being given invalid HTML code to parse, the difficulty factor increases even more.
With a lot of effort and good understanding of the more esoteric parts of regex, it can be done, with a reasonable degree of reliability. But it's never going to be perfect -- there's always going to be the possibility of your regex not working if it's fed with something it doesn't expect.
By contrast, parsing it with the DOM is much much simpler -- as demonstrated, with the right libraries, it can be a single line of code (and very easy to read, unlike the horrific regex you'd need to write). It'll also be much more efficient to run, and gives you the ability to do other search operations on the same chunk of HTML, without having to re-parse it all again.

Categories