Replacing all english quotes with german quotes - javascript

im here to ask, if someone can help me with quotation and syntax checking.
im aware of the question solution 1, but i don't fully understand that solution.
here is an example, fully integrated into a website and humbly ask, if anyone can find an error?
function rewriteQuotes(){
var all_p = document.querySelectorAll(`.content_container`);
var regex_s = /[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?#\[\]^_`{|}~]/;
for (var i = 0; i < all_p.length; i++) {
if (all_p[i] != null) {
var all_nodes = all_p[i].querySelectorAll("*");
for (var k = 0; k < all_nodes.length; k++) {
if (all_nodes[k].childNodes.length > 0) {
var all_children = all_nodes[k].childNodes;
for (var t = 0; t < all_children.length; t++) {
if (all_children[t].nodeName == "#text") {
all_children[t].textContent = all_children[t].textContent.replace(/"/g,"\“");
all_children[t].textContent = all_children[t].textContent.replace(/\s\“/g,"\ „");
if (all_children[t].textContent.charAt(0)== "\“") {
if (all_children[t].textContent.charAt(1) === "") {
} else {
var char_1 = all_children[t].textContent.charAt(1);
if (regex_s.test(char_1)) {
} else {
all_children[t].textContent = "\„" + all_children[t].textContent.substring(1);
}
}
}
}
}
}
}
}
}
};
document.addEventListener('DOMContentLoaded',function(){
setTimeout(function(){
rewriteQuotes();
},1);
});
<div class="content_container">
<h2>"Hello"</h2>
<p>my "aunti" was driving over the "cat" with her "<em>skateboard</em>".</p>
</div>

You can simplify your regex and capture groups of "..." and then replace the quotes of those groups with your desired ones:
const regex = /"(.*?)"/g;
const str = `my "aunti" was driving over the "cat" with her "car"`;
const subst = `„$1“`;
const result = str.replace(regex, subst);
console.log('Original: ', str);
console.log('Result: ', result);

Related

String Permutation function not working right

First of all sorry for bothering with a question asked several times before.But I have to say that I did read through the related questions about string permutations and I could not figure out the actual problem with the code I have below. I want to return the combinations of a string.Please help me out in finding the mistake ! PS: I have just started learning javascript!
var result = [];
function doPerm(prefix, suffix, result) {
if (suffix.length === 0)
result.push(prefix);
else {
for (i = 0; i < suffix.length; i++) {
doPerm(prefix + suffix.charAt(i), suffix.slice(0, i) + suffix.slice(i + 1), result);
}
}
}
function permAlone(str) {
var prefix = "";
var suffix = str;
doPerm(prefix, suffix, result);
return result;
}
console.log(permAlone('aab'));
INPUT:'aab'
OUTPUT:[aab,aab,aba,aba,baa,baa]
Your logic was correct actually, you just declared i without var in for loop which made it global and was giving you errors. It seems to be working once that is corrected:
var result = [];
function doPerm(prefix, suffix, result) {
if (suffix.length === 0)
result.push(prefix);
else {
for (var i = 0; i < suffix.length; i++) {
doPerm(prefix + suffix.charAt(i), suffix.slice(0, i) + suffix.slice(i + 1), result);
}
}
}
function permAlone(str) {
var prefix = "";
var suffix = str;
doPerm(prefix, suffix, result);
return result;
}
console.log(permAlone('aab'));
This is a bit of on the back of a piece of paper thinking but.
for(i;i<string.length;i++) {
var s = string.slice(i,i+1);
var c = string.charAt(i);
var q = s.split("");
for(b=0;b<q.length;b++) {
var newArray = q.slice();
newArray.splice(b,0,c);
result.push(newArray.join());
}
}
does that work?
UPDATE this seems to work!
<script>
var string = "aab";
var result = [];
for(i=0;i<string.length;i++) {
var c = string.charAt(i);
var q = string.split("");
q.splice(i,1);
console.log("first");
console.log(q);
console.log(c);
for(b=0;b<q.length;b++) {
var newArray = q.slice();
newArray.splice(b,0,c);
result.push(newArray.join());
}
}
console.log(result);
</script>

Uglify unable to work for nested if-else

I'm using this online tool to uglify my code although i'm using grunt-uglify to do the same but same error with this also, It works fine to minify the code but when i evaluate this code it returns an error of expected :. since it's not working for nested if-else case.
Sample code.
$._ext_ILST = {
changeColorLabel: function() {
spots = app.documents[0].spots;
var colorLabelArray = new Array();
for (var i = 0; i < spots.length; i++) {
try {
if (spots[i].toString() !== "[Spot]") {
if (spots[i].name.indexOf('$') == 0) {
colorLabelArray.push(spots[i].name.substring(1, spots[i].name.length));
}
}
} catch (e) {}
}
var colorInfo = getColorInfromation();
var obj = {}
if (colorInfo.length > 0)
colorLabelArray = [];
for (var i = 0; i < colorInfo.length; i++) {
colorLabelArray.push(colorInfo[i].colorName);
if ((colorInfo[i].hasOwnProperty('colorType') && colorInfo[i].colorType != "teamColorVariable")) {
if (colorInfo[i].isGarmentColor) {
obj[colorInfo[i].colorName] = "G"
} else {
obj[colorInfo[i].colorName] = "D"
}
} else if (!colorInfo[i].hasOwnProperty('colorType')) {
if (colorInfo[i].isGarmentColor) {
obj[colorInfo[i].colorName] = "G"
} else {
obj[colorInfo[i].colorName] = "D"
}
}
}
var mainColorObj = {
colorLabelArray: colorLabelArray,
colorMapArray: obj
}
return JSON.stringify(mainColorObj);
}
}
Minified ouput -
$._ext_ILST = {
changeColorLabel: function() {
spots = app.documents[0].spots;
for (var a = new Array, b = 0; b < spots.length; b++) try {
"[Spot]" !== spots[b].toString() && 0 == spots[b].name.indexOf("$") && a.push(spots[b].name.substring(1, spots[b].name.length))
} catch (c) {}
var d = getColorInfromation(),
e = {};
d.length > 0 && (a = []);
for (var b = 0; b < d.length; b++) a.push(d[b].colorName), d[b].hasOwnProperty("colorType") && "teamColorVariable" != d[b].colorType ? d[b].isGarmentColor ? e[d[b].colorName] = "G" : e[d[b].colorName] = "D" : d[b].hasOwnProperty("colorType") || (d[b].isGarmentColor ? e[d[b].colorName] = "G" : e[d[b].colorName] = "D");
var f = {
colorLabelArray: a,
colorMapArray: e
};
return JSON.stringify(f)
}
};
Any help will be appreciated.
Thanks,
Upendra sengar
You should lint your JS first.
Here’s a post-lint (and slightly modified) version of your code:
/* globals app, $, getColorInfromation */
(function(app, $, JSON, undefined) {
$._ext_ILST = {
changeColorLabel: function() {
var spots = app.documents[0].spots;
var colorLabelArray = [];
var i;
for (i = 0; i < spots.length; i++) {
try {
if (spots[i].toString() !== "[Spot]") {
if (spots[i].name.indexOf('$') === 0) {
colorLabelArray.push(spots[i].name.substring(1, spots[i].name.length));
}
}
} catch (e) {}
}
var colorInfo = getColorInfromation();
var obj = {};
if (colorInfo.length > 0)
colorLabelArray = [];
for (i = 0; i < colorInfo.length; i++) {
colorLabelArray.push(colorInfo[i].colorName);
if ((colorInfo[i].hasOwnProperty('colorType') && colorInfo[i].colorType != "teamColorVariable")) {
if (colorInfo[i].isGarmentColor) {
obj[colorInfo[i].colorName] = "G";
} else {
obj[colorInfo[i].colorName] = "D";
}
} else if (!colorInfo[i].hasOwnProperty('colorType')) {
if (colorInfo[i].isGarmentColor) {
obj[colorInfo[i].colorName] = "G";
} else {
obj[colorInfo[i].colorName] = "D";
}
}
}
var mainColorObj = {
colorLabelArray: colorLabelArray,
colorMapArray: obj
};
return JSON.stringify(mainColorObj);
}
};
}(app, $, JSON));
Note that I wrapped your code in an IIFE to give you better uglification results. Also notice that I only did a topical sweeping of your code … there’s more that I think you could do to make it better (e.g., brackets around if statements, I personally like to explicitly hoist all my vars, etc.).
Next, I quickly googled for an online minification/uglification tool and copy/pasted the linted version of your code; here’s the result:
!function(o,r,e,a){r._ext_ILST={changeColorLabel:function(){var r,a=o.documents[0].spots,n=[];for(r=0;r<a.length;r++)try{"[Spot]"!==a[r].toString()&&0===a[r].name.indexOf("$")&&n.push(a[r].name.substring(1,a[r].name.length))}catch(t){}var l=getColorInfromation(),c={};for(l.length>0&&(n=[]),r=0;r<l.length;r++)n.push(l[r].colorName),l[r].hasOwnProperty("colorType")&&"teamColorVariable"!=l[r].colorType?l[r].isGarmentColor?c[l[r].colorName]="G":c[l[r].colorName]="D":l[r].hasOwnProperty("colorType")||(l[r].isGarmentColor?c[l[r].colorName]="G":c[l[r].colorName]="D");var m={colorLabelArray:n,colorMapArray:c};return e.stringify(m)}}}(app,$,JSON);
Not sure if that’s what you’re looking for, and/or if the code still functions, but hopefully that puts you in the right direction?

How can I check a string of words to see if they are an anagram of one word

I am trying to figure out a javascript function that will help resolve this test. I need to be able to determine if the string of words (var matches) that is given is an anagram of the word that I am running through (var subject). In this case there would not be a match. Any and all help will be greatly appreciated. Thank you in advance!
var anagram = require('./anagram');
describe('Anagram', function() {
it("no matches",function() {
var subject = anagram("diaper");
var matches = subject.matches([ "hello", "world", "zombies", "pants"]);
expect(matches).toEqual([]);
});
});
This is what I have so far:
for (var i = 0; i < matches.length; i++) {
if (subject.length != matches[i].length) {
return false
} else if (subject.length == matches[i].length){
var anagram = function(subject, matches) {
return subject.split("").sort("").join("") === matches[i].split("").sort("").join("");
};
}
Here is the fiddle:
http://jsfiddle.net/hn8r4v3u/2/
I alphabetized the letters within the word, as you were doing, in a function.
function getAlphaSortedWord(word) {
var baseWordCharArray = word.split("");
baseWordCharArray.sort();
return baseWordCharArray.join("");
}
The code has a set up:
var baseWord = getAlphaSortedWord("bob");
var thingsToCheck = ["obb", "2", "bob", "", "bo", "ob"];
And then solves it two ways, once with filter and once without it.
var matches = _.filter(thingsToCheck, function (str) {
return (baseWord === getAlphaSortedWord(str));
});
var matches2 = [];
for (index = 0; index < thingsToCheck.length; index++) {
if (baseWord === getAlphaSortedWord(thingsToCheck[index])) {
matches2.push(thingsToCheck[index]);
}
}
You should be able to use these to tie in with your real data for the test to pass.
NOTE, I would add some sanity for "is string" to my function if this is going to be production code.
Found here and it works: https://gist.github.com/AlbertoElias/10005056
function areAnagrams(a, b) {
var c = false;
if (a.length !== b.length) {
return c;
}
var hashMap = {};
var char;
var i;
for (i=0;i<a.length;i++) {
char = a[i];
hashMap[char] = hashMap[char] !== undefined ? hashMap[char]+1 : 1;
}
for (i=0;i<b.length;i++) {
char = b[i];
if (hashMap[char] !== undefined) {
if (hashMap[char] > 1) {
hashMap[char]--;
} else {
delete hashMap[char];
}
} else {
return c;
}
}
if (Object.keys(hashMap).length === 0) c = true;
return c;
}

Change one letter of innerHTML

I have a for loop like this:
for(var i = 0; i < woord.length; i++) {
if(woord[i] === letter) {
goed = true;
woordContainer.innerHTML[i] = woord[i];
}
}
But the text in the woordContainer doesn't change on the page. I tried logging woord[i] to the console and it show the correct letter.
EDIT:
Let me share the complete code, so you can understand it better:
(it is a hangman game)
var store,
woord,
wrapper,
woordContainer,
letterInput,
gokButton,
pogingen,
pogingenText;
window.onload = function() {
store = new Persist.Store("galgje");
woord = store.get("woord");
pogingen = 10;
wrapper = document.getElementById("wrapper");
woordContainer = document.getElementById("woordContainer");
letterInput = document.getElementById("letterInput");
gokButton = document.getElementById("gokButton");
pogingenText = document.getElementById("pogingenText");
if (!woord) {
document.location.href = "./index.html";
}
for (var i = 0; i < woord.length; i++) {
woordContainer.innerHTML += ".";
}
wrapper.appendChild(woordContainer);
gokButton.onclick = function() {
var letter = letterInput.value.toLowerCase();
var goed = false;
if(letter) {
for(var i = 0; i < woord.length; i++) {
if(woord[i] === letter) {
goed = true;
woordContainer.innerHTML = woord[i];
}
}
if(!goed) {
pogingen--;
if(pogingen === 0) {
document.location.href = "./af.html";
}
pogingenText.innerHTML = "Pogingen: " + pogingen;
}
letterInput.value = "";
}
return false;
}
}
If you want to replace the character int woordContainer.innerHTML at index i, with the one in woord[i], you can do it like this:
if(woord[i] === letter) {
goed = true;
var temp = woordContainer.innerHTML
woordContainer.innerHTML = temp.substr(0, i) + woord[i] + temp.substr(i + woord[i].length);
}

Automatically paraphrasing sentences in JavaScript

In JavaScript, is it possible to automatically replace a regular expression in a sentence with a randomly generated match of that regular expression? I'm trying to use this approach to automatically paraphrase a sentence using a list of regular expressions, like so:
replaceWithRandomFromRegexes("You aren't a crackpot! You're a prodigy!", ["(genius|prodigy)", "(freak|loony|crackpot|crank|crazy)", "(You're |You are |Thou art )", "(aren't|ain't|are not)"])
Here, each match of each regular expression in the input string should be replaced with a randomly generated match of the regular expression.
function replaceWithRandomFromRegexes(theString, theRegexes){
//For each regex in theRegexes, replace the first match of the regex in the string with a randomly generated match of that regex.
}
This seems to be much simpler than you think. How about:
function randomReplace(subject, groups, wordsOnly) {
var meta = /([.?*+^$[\]\\(){}|-])/g, all = {};
groups.forEach(function(group) {
group.forEach(function(word) { all[word] = group })
});
var r = Object.keys(all).
sort(function(x, y) { return y.length - x.length }).
map(function(x) { return x.replace(meta, "\\$&") }).
join("|");
if(wordsOnly)
r = "\\b(" + r + ")\\b";
return subject.replace(new RegExp(r, "g"), function($0) {
return all[$0][Math.floor(Math.random() * all[$0].length)]
});
}
Example:
s = randomReplace(
"You aren't a crackpot! You're a prodigy!",
[
["genius", "prodigy"],
["freak", "loony", "crackpot", "crank", "crazy"],
["You're ", "You are ", "Thou art "],
["aren't", "ain't", "are not"]
]
);
console.log(s) // You ain't a crank! Thou art a genius!
The expansion function, as discussed in the comments, could be like this:
function expand(s) {
var d = [];
function product(a, b) {
var p = [];
a.map(function(x) { b.map(function(y) { p.push(x + y) })});
return p;
}
function reduce(s) {
var m;
if(s.indexOf("|") >= 0)
return [].concat.apply([], s.split("|").map(reduce));
if(m = s.match(/~(\d+)(.*)/))
return product(reduce(d[m[1]]), reduce(m[2]));
return [s];
}
function add($0, $1) { d.push($1); return '~' + (d.length - 1) }
s = s.replace(/([^()|]+)/g, add);
for(var r = /\(([^()]*)\)/g; s.match(r);)
s = s.replace(r, add);
return reduce(s);
}
Example:
z = "(He|She|It|(B|R)ob(by|)) (real|tru|sure)ly is"
console.log(expand(z))
Result:
[
"He really is",
"He truly is",
"He surely is",
"She really is",
"She truly is",
"She surely is",
"It really is",
"It truly is",
"It surely is",
"Bobby really is",
"Bobby truly is",
"Bobby surely is",
"Bob really is",
"Bob truly is",
"Bob surely is",
"Robby really is",
"Robby truly is",
"Robby surely is",
"Rob really is",
"Rob truly is",
"Rob surely is"
]
Yes, this is certainly possible. I created a function called replaceWithRandomFromRegexes to accomplish this task.
http://jsfiddle.net/KZyZW/2/
for(var i = 0; i < 10; i++){
document.body.innerHTML += (replaceWithRandomFromRegexes("You aren't a crackpot! You're a prodigy!", ["(genius|prodigy)", "(freak|loony|crackpot|crank|crazy)", "(You're |You are |Thou art )", "(aren't|ain't|are not)"]))+"<br/>";
}
function replaceWithRandomFromRegexes(theString, theRegexes) {
//alert(theRegexes);
for (var i = 0; i < theRegexes.length; i++) {
theString = globalReplaceWithRandomFromRegex(theString, theRegexes[i]);
//alert(theRegexes[i]);
}
//alert("All the regexes: " + theRegexes);
return theString;
}
function globalReplaceWithRandomFromRegex(theString, theRegexString) {
var theRegex = new RegExp(theRegexString, "gi");
//replace all matches of theRegex with '<thing to replace>'
theString = theString.replace(theRegex, "<thing to replace>")
//replace the first match of '<thing>'
while (theString.indexOf("<thing to replace>") != -1) {
theString = theString.replace("<thing to replace>", getRandomStringFromNestedParentheses(theRegexString));
}
//alert(theString);
return theString;
}
function getRandomStringFromNestedParentheses(theString) {
while (theString.indexOf("(") != -1) {
theString = replaceInFirstParentheses(theString);
}
return theString;
}
function replaceInFirstParentheses(theString) {
//find the index of the first parentheses
var parenthesesIndex = theString.indexOf("(");
var randomString = getRandomStringInsideParentheses(theString, parenthesesIndex);
//alert(randomString);
//theString = theString.replace();
//find the string to replace
var stringToReplace = theString.substring(parenthesesIndex, getCorrespondingParenthesesIndex(theString, parenthesesIndex) + 1);
//alert(stringToReplace);
theString = theString.replace(stringToReplace, randomString);
//alert(theString);
return theString;
}
function getRandomStringInsideParentheses(string, parenthesesIndex) {
var stringArray = getStringsInsideParentheses(string, parenthesesIndex)
//find out how to pick random in a range
//pick something random from the array declared above
//var theMin = 0;
//var theMax = stringArray.length-1;
var randomNumber = Math.floor(Math.random() * stringArray.length);
return stringArray[randomNumber];
}
function getStringsInsideParentheses(string, parenthesesIndex) {
//alert("calling function getStringsInsideParentheses");
var theString = getStringFromParentheses(string, parenthesesIndex);
for (var i = 0; i < theString.length; i++) {
var theParenthesesNum = getParenthesesNum(theString, i);
if (theString[i] == '|') {
//alert("Parentheses num: " + theParenthesesNum);
if (theParenthesesNum == 0) {
theString = theString.substring(0, i) + "|" + theString.substring(i, theString.length);
i++;
}
}
}
//alert(theString);
return theString.split("||")
}
function getStringFromParentheses(theString, parenthesesIndex) {
return theString.substring(parenthesesIndex + 1, getCorrespondingParenthesesIndex(theString, parenthesesIndex))
}
function getCorrespondingParenthesesIndex(theString, openingParenthesesIndex) {
if (!parenthesesAreMatching(theString)) {
writeMessage("Error: The parentheses do not match!");
return false;
}
if (theString.charAt(openingParenthesesIndex) != "(") {
writeMessage("Error: The index must be an opening parentheses!");
return false;
}
var num = 0;
for (var i = openingParenthesesIndex; i < theString.length; i++) {
if (theString.charAt(i) == "(") {
num++;
}
if (theString.charAt(i) == ")") {
num--;
}
if (num == 0) {
return i;
}
}
writeMessage("Error: The parentheses do not match!");
return false;
}
function parenthesesAreMatching(theString) {
var num = 0;
for (var i = 0; i < theString.length; i++) {
if (theString.charAt(i) == "(") {
num++;
}
if (theString.charAt(i) == ")") {
num--;
}
}
if (num == 0) {
return i;
} else {
return false;
}
}
function getParenthesesNum(theString, index) {
//this should be based on parenthesesAreMatching, but stopping at index
var num = 0;
for (var i = 0; i < index; i++) {
if (theString.charAt(i) == "(") {
num++;
}
if (theString.charAt(i) == ")") {
num--;
}
}
return num;
}
The original sentence was You aren't a crackpot! You're a prodigy! Here are some automatically paraphrased versions of this sentence, as produced by this script:
You are not a freak! Thou art a genius!
You aren't a crackpot! You're a prodigy!
You ain't a crackpot! You are a genius!
You ain't a freak! You're a prodigy!
You are not a crackpot! You are a prodigy!
You are not a loony! You're a prodigy!
You are not a loony! You are a genius!
You are not a loony! You are a prodigy!
You ain't a crackpot! Thou art a prodigy!
You are not a loony! Thou art a prodigy!

Categories