Javascript not printing variable as expected - javascript

For the following javascript
for (i = 0; i < agentIds.length; i++) {
var agentId = agentIds[i];
var variable1 = "isWrapup_"+agentId;
alert(variable1);
var text2 = "var isWrapup = JSON.parse(${"+variable1+"});";
alert(text2);
}
The first alert is printed as: isWrapup_efdbf4e71c9c6997eb705a71a6819b78
The second alert is printed as : var isWrapup = JSON.parse('+variable1+');
I'm expecting to print it as : var isWrapup = JSON.parse('isWrapup_efdbf4e71c9c6997eb705a71a6819b78')
What have I done wrong here?

The text formatting needs to be corrected, concat works better in these situations, here is why. Try:
for (i = 0; i < agentIds.length; i++) {
var agentId = agentIds[i];
var variable1 = "isWrapup_"+agentId;
alert(variable1);
var str1 = "var isWrapup = JSON.parse(${"
var str2 = "});"
var text2 = str1.concat(variable1,str2);;
alert(text2);
}

All you need to do currently is remove that '$' from the the picture and thats it.
var text2 = "var isWrapup = JSON.parse({" + variable1 + "});"; // works fine here : https://www.javascript.com/try
Also, you are unintentionally using an Escape_character#JavaScript
The Point-to-Point Protocol uses the 0x7D octet (\175, or ASCII: } )
as an escape character
In which case you can try something like this in your code :
var text2 = "var isWrapup = JSON.parse({{" + variable1 + "}});";
Hope it helps.

Related

Javascript spilt function does not recognise one of the tabs in my string

I have a string with tab-separated data copied from Excel. The javascript split does not recognise the 2nd tab in the string. I have pasted the string into notepad++ to see the tabs and they are all there. Exploding the string in PHP works fine. The test code is:
function testTab(str) {
var strSplit = str.split('\t');
for (i=0; i < strSplit.length; i++){
console.log('strSplit['+i+'] = '+strSplit[i]);
}
}
The console output (where the tab between 1st and 2nd item is not recognised):
strSplit[0] = 0.02194 0.028940568
strSplit[1] = 0.05227
strSplit[2] = 0.040229885
strSplit[3] = 0.04650
strSplit[4] = 0.035630689
strSplit[5] = 0.07055
strSplit[6] = 0.015557256
strSplit[7] = 0.01960
strSplit[8] = 0.03527
strSplit[9] = 0.05276
strSplit[10] = 0.05669
strSplit[11] = 0.05680
strSplit[12] = 0.04464
strSplit[13] = 1
Unsure if the string copies correctly with all tabs, but here it is:
const str = `0.02194 0.028940568 0.05227 0.040229885 0.04650 0.035630689 0.07055 0.015557256 0.01960 0.03527 0.05276 0.05669 0.05680 0.04464 1`;
function testTab(str) {
var strSplit = str.split('\t');
for (i = 0; i < strSplit.length; i++) {
console.log('strSplit[' + i + '] = ' + strSplit[i]);
}
}
testTab(str)
Thanks for your suggestions, it inspired me to review all options.
I changed the delimiters in the regex so that the split now reads:
var strSplit = str.split(/\t/);
For some reason it now works.

How to output Javascript string with character encoding

So - I have a string in javascript liks so:
var foo = "Hello™";
I need to print this out in HTML (via JS) so it looks like this:
Hello™
Sounds easy, but I obviously am missing something cause I can't figure out a simple solution for it yet.
EDIT - here is more code:
var label = document.createElement('label');
var foo = selectData.options[i][1]; // this is "Hello&trade";
label.innerHTML = foo;
container.appendChild( label );
Just append it into the innerHTML property.
innerHTML will html encode the given input and that append it to the node.
var foo = "Hello™";
document.getElementById('label').innerHTML = foo;
<label id="label"></label>
First separate the '&trade' and check for it in an if-statement and then give var the value of the hexcode equivalent which is 'u2122' then the rest of the code should do the work.
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
String.prototype.hexDecode = function(){
var j;
var hexes = this.match(/.{1,4}/g) || [];
var back = "";
for(j = 0; j<hexes.length; j++) {
back += String.fromCharCode(parseInt(hexes[j], 16));
}
return back;
}
var str = "\u2122";
var newStr = (str.hexEncode().hexDecode());
var foo = "Hello" + newStr;
console.log(foo);

Remove HTML tags in script

I've found this piece of code on the internet. It takes a sentence and makes every single word into link with this word. But it has weak side: if a sentence has HTML in it, this script doesn't remove it.
For example: it replaces '<b>asserted</b>' with 'http://www.merriam-webster.com/dictionary/<b>asserted</b>'
Could you please tell me what to change in this code for it to change '<b>asserted</b>' to 'http://www.merriam-webster.com/dictionary/asserted'.
var content = document.getElementById("sentence").innerHTML;
var punctuationless = content.replace(/[.,\/#!$%\؟^?&\*;:{}=\-_`~()”“"]/g, "");
var mixedCase = punctuationless.replace(/\s{2,}/g);
var finalString = mixedCase.toLowerCase();
var words = (finalString).split(" ");
var punctuatedWords = (content).split(" ");
var processed = "";
for (i = 0; i < words.length; i++) {
processed += "<a href = \"http://www.merriam-webster.com/dictionary/" + words[i] + "\">";
processed += punctuatedWords[i];
processed += "</a> ";
}
document.getElementById("sentence").innerHTML = processed;
This regex /<{1}[^<>]{1,}>{1}/g should replace any text in a string that is between two of these <> and the brackets themselves with a white space. This
var str = "<hi>How are you<hi><table><tr>I<tr><table>love cake<g>"
str = str.replace(/<{1}[^<>]{1,}>{1}/g," ")
document.writeln(str);
will give back " How are you I love cake".
If you paste this
var stripHTML = str.mixedCase(/<{1}[^<>]{1,}>{1}/g,"")
just below this
var mixedCase = punctuationless.replace(/\s{2,}/g);
and replace mixedCase with stripHTML in the line after, it will probably work
function stripAllHtml(str) {
if (!str || !str.length) return ''
str = str.replace(/<script.*?>.*?<\/script>/igm, '')
let tmp = document.createElement("DIV");
tmp.innerHTML = str;
return tmp.textContent || tmp.innerText || "";
}
stripAllHtml('<a>test</a>')
This function will strip all the HTML and return only text.
Hopefully, this will work for you
if you need to remove HTML tags And HTML Entities You can use
const text = '<p>test content </p><p><strong>test bold</strong> </p>'
text.replace(/<[^>]*(>|$)| |‌|»|«|>/g, '');
the result will be "test content test bold"

ActiveXObject Number of rows counter

I have this piece of code:
function GetData(evt){
var adresses = new Array();
var j = 0;
var excel = new ActiveXObject("Excel.Application");
var fil = document.getElementById("file");
var excel_file = excel.Workbooks.Open(fil.value);
var excel_sheet = excel.Worksheets(1);
for(var i=2;i<500;i++){
var morada = excel_sheet.Range("E"+ i );
var localidade = excel_sheet.Range("C"+ i );
var pais = excel_sheet.Range("A"+i);
adresses[j] = (morada + ", " + localidade + ", " + pais);
j++;
}
for(var k = 0; k<j; k++) {
codeAddress(adresses[k]);
}
}
It receives an excel file and processes the data like I want. The thing is, it is very hard coded.
For instant, in this for:
for(var i=2;i<500;i++)
I am using 500, but I would like to use the number of rows in the sheet. I have already tried a few things like rows.count and whatever and I gave some alerts to see the results, but I just can't find the one who tells me the number of rows.
Anyone know how to do it?
Try that :
excel_sheet.UsedRange.Rows.Count
Does it works ?

appending values to textbox using for loop javascript

I am trying to add values to a textbox when looping through an array when checking checkboxes but as it is at the moment getting undefined.
Advice perhaps as to why the values are 'undefined'
var txtBoxValues = [];
$(document).on("click", "input[name=chkRelatedTopics]", function () {
var nameAdminUser = $(this).val();
var txtBox = document.getElementById("txtTraningTopics");
txtBox.value = '';
txtBoxValues.push(nameAdminUser);
for (var i in txtBoxValues) {
var str = txtBoxValues[i].value;
txtBox.value += str + '; ';
}
});
nameAdminUser is already a string, so don't take .value from it.
You could replace
var str = txtBoxValues[i].value;
with
var str = txtBoxValues[i];
But instead of using this loop, and assuming you don't want, as I suppose, the last ";", you could also do
txtBox.value = txtBoxValues.join(';');
nameAdminUser seems to be a String and in your for loop you expect an object. What if you simply do:
for (var i in txtBoxValues) {
var str = txtBoxValues[i];
txtBox.value += str + '; ';
}

Categories

Resources