When I run this code, the variable items only appends 9999 chars and rest is truncated. I got a few answers in the previous post but the problem still persists.
var items = [];
for (var i = 1; i < 400; i++) {
items.push('{"Key":' + '"this is a javascript value"' +
",'+'" + '"Value"' + ':' + '"this is value"}');
}
alert(items);
Help!
You are alerting the value which means the array is converted to a String and then put in an alert box. Most probably, the String is cut off to some maximum length, otherwise it just won't fit on the screen or in the box for graphical reasons.
When tried in-memory and only alerting the lengths, everything seems OK, also the toString() returns the correct length. I tried 4000 elements and analyzing the lengths: http://jsfiddle.net/LWD2h/1/.
There is a workaround for the 10,000 character limit for an alert (in FireFox, untested in other browsers). If you are only wanting to display the alert for debugging purposes, and not to a user then you can use the prompt statement. The code would look like:
var myLongString = "A really long string";
prompt('',myLongString);
When this displays, you only see one line of text in the prompt, but you can click into the prompt box and select all the text and paste it into an editor to do with as you want. It would be terrible to do this to your users, but it's great for quick and dirty debugging. The prompt statement strips all your line feeds, so prior to invoking it you should convert them to some other string, then convert them back in your text editor.
Incorporating that code into the above code gives:
var myLongString= "A\nreally\nlong\nstring\nwith\nline\nfeeds.";
prompt('', myLongString.replace(/\n/g,"=##=");
After pasting the string into your text editor you would search and replace '=##=' with '\n'.
Related
I'm getting an error with my code below. I am trying to make a calculator, and I am using strings as input and typecasting in order to solve. The calculator was working fine, but now I am trying to add an ans button to allow for having equations based on previous answer. I am having an issue with the substrings now, and in equations where ans comes first like 'ans+88" I get NaN as a result and 88 turns into undefined. But when I switch the substring parameters it messes it up for other types of equations as described in the comments below.
link to repository
else if(equation.indexOf("+") != -1){
//this finds the the index of +
let pInd = equation.indexOf("+")
/*before I added this, it worked properly, firstValue would get the firstvalue
secondvalue would get the second value and it added correctly
the point of the if statement is to replace ans with props.prevResult which is
the previous answer from the previous entered equation. After it replaces it
removes the whitespace*/
if(equation.includes("ᴀɴs")){
equation = equation.replace(/ᴀɴs/gi, String(props.prevResult))
//my attempt to remove whitespace since i thought it might be the issue
// but now I'm pretty sure the issue is with substring.
equation = equation.replace(/\s/g, '')
}
equation = String(equation)
firstVal = equation.substring(0,pInd)
//this line is where the error seems to come from
secondVal = equation.substring(pInd+1,equation.length)
/* when ans is first such as in 'ans + 9" 9 becomes undefined ans stays
correct. I tried replacing it with pInd+1, equation.length-1, but that
made it so that equations like '9+ans' were cut short,
and regular ('1+55') equations also broke.*/
result = parseFloat(firstVal)+parseFloat(secondVal)
props.setInput(result)
props.setPrevResult(result)
setResultGot(true)
}
The solution #james gave solved the issue, the position of the + sign was obviously going to change after I replaced ans, so that line just had to be moved to after the replacement, silly mistake, I appreciate the help.
Idea
I'm making a configuration editor for a game, and I want to replace some of the strings with HTML code tooltips that would summarize what the command does, such as gravity or ammo.
I've tried data.replace(replacet, replacew), both (replace this) and (replace with) being array of strings and no, its not working.
JavaScript
function updateStrings() {
var replacet = "sv_cheats ";
var replacew = " <mark>sv_cheats</mark> ";
var data = document.getElementById('data').innerHTML;
document.getElementById('data').innerHTML = data.replace(replacet, replacew);
}
document.addEventListener('onkeydown', document.getElementById('data'), updateStrings());
Point
This code I'd say roughly works, but the caret position is set to 0 (beginning) on every key press as the JavaScript tries to append every character given at the first position which clearly is not supposed to be happening.
Question is are there any frameworks that do this automatically? I'd want something like in VS Code when if you hover over a function it tells you the parameters and such, something like that would be awesome to have!
Thanks!
Trying something new, I was attempting to highlight text on this wikia page using javascript within the address bar (i.e. using "javascript:[code]").
When running the following code sample through Chrome's console, it produces the desired effect. When running it from the address bar, it results in only the affected text -- the rest of the page body is removed.
javascript:txt = document.getElementById("Ballas.27_Rebellion_and_Allying_With_Hunhow").parentElement.nextElementSibling;index = txt.innerHTML.indexOf(", but")+2;txt.innerHTML = txt.innerHTML.substring(0,index)+"<span style='background-color:yellow;'>"+txt.innerHTML.substring(index,index+40)+"</span>"+txt.innerHTML.substring(index+40);
Note: if you want to try this you will have to manually type javascript: into the address bar before pasting the code, as Chrome automatically removes it.
I'm curious as to why this would be, and also if there is a way to stop the address bar from removing the rest of the page body. Can anyone offer insight?
Thanks.
The quick solution to the problem you're experiencing is to add false; to the end of your query. This will prevent Chrome from removing the text from your page and should give you the result you expect.
Here's the fixed code:
javascript:txt = document.getElementById("Ballas.27_Rebellion_and_Allying_With_Hunhow").parentElement.nextElementSibling;index = txt.innerHTML.indexOf(", but")+2;txt.innerHTML = txt.innerHTML.substring(0,index)+"<span style='background-color:yellow;'>"+txt.innerHTML.substring(index,index+40)+"</span>"+txt.innerHTML.substring(index+40);false;
To fully answer the question, let me quickly explain what is happening. I'll start by splitting up your JS a bit to make it easier to read.
txt = document.getElementById("Ballas.27_Rebellion_and_Allying_With_Hunhow").parentElement.nextElementSibling;
index = txt.innerHTML.indexOf(", but")+2;
txt.innerHTML = txt.innerHTML.substring(0,index) +
"<span style='background-color:yellow;'>" +
txt.innerHTML.substring(index,index+40) +
"</span>"+txt.innerHTML.substring(index+40);
What you'll note is that the final statement is an assignment operation. In JavaScript the result of an assignment operation is the value of the assignment. In other words, if we say return x = 1 we will both set the value of x to 1 and return the value 1.
This brings us to the reason why Chrome is replacing your page content. The JavaScript you're providing is returning the content of the txt element (the paragraph you're deciding to highlight) and this is then being treated as the content of your new page, the same way that visiting data:text/plain,hello world or javascript:"hello world" in your browser will show the text "hello world"even though you haven't explicitly visited a website.
To fix this, you can return a falsey value in JavaScript - this means any one of the following:
0
false
[]
null
undefined
Hence, adding false; at the end of your JavaScript will have Chrome run the code but not show the resulting text and will prevent it from changing the page content on you unexpectedly.
Javascript newb here. Creating a bookmarklet to automate a simple task at work. Mostly a learning exercise. It will scan a transcript on CNN.com, for instance: (http://transcripts.cnn.com/TRANSCRIPTS/1302/28/acd.01.html). It will grab the lead stories at the top of the page, the name and title of the guests on the show, and format them so that they can be copy pasted into another document.
I've come up with a simple version that includes some jQuery that grabs the subheading and then uses a regular expression to find the names of the guests (it will also exclude everything between (begin videoclip) and (end videoclip), but I haven't gotten that far yet. It then alerts them (will eventually print them in a pop-up window, alert is just for troubleshooting purposes).
I'm using http://benalman.com/code/test/jquery-run-code-bookmarklet/ to create the bookmarklet. My problem is that once the bookmarklet is created it is completely unresponsive. Click on it and nothing happens. I've tried minimizing the code first with no result. My guess is that cnn.com's javascript is conflicting with mine but I'm not sure how to get around that. Or do I need to include some code to load and store the text on the current page? Here's the code (I've included comments, but I took these out when I used the bookmarklet generator.) Thanks for any help!
//Grabs the subheading
var leadStories=$(".cnnTransSubHead").text();
//Scans the webpage for guest name and title. Includes a regular expression to find any
//string that starts with a capital letter, includes a comma, and ends in a colon.
var scanForGuests=/[A-Z ].+,[A-Z0-9 ].+:/g;
//Joins the array created by scanForGuests with a semicolon instead of a comma
var guests=scanForGuests.join(‘; ‘);
//Creates an alert in the proper format including stories and guests.
alert(“Lead Stories: “ + leadStories + “. ” + guests + “. SEE TRANSCRIPT FIELD FOR FULL TRANSCRIPT.“)
Go to the page. Open up developer tools (ctrl+shift+j in chrome) and paste your code in the console to see what's wrong.
The $ in var leadStories = $(".cnnTransSubHead").text(); is from jQuery and the link provided does not have jQuery loaded into the page.
On any modern browser you should be able to achieve the same results without jQuery:
var leadStories = document.getElementsByClassName('cnnTransSubHead')
.map(function(el) { return el.innerText } );
next we have:
var scanForGuests=/[A-Z ].+,[A-Z0-9 ].+:/g;
var guests=scanForGuests.join('; ');
scanForGuests IS a regular expression, you never actually matched it to anything - so .join() is going to throw an error. I'm not exactly sure what you're trying to do. Are you trying to scan the full text of the page for that regex? In that case something like this would be your best bet
document.body.innerText.match(scanForGuests);
keep in mind that while innerText removes html markup, it's far from perfect and what pops up in it is very much at the mercy of how the page's html is structured. That said, on my quick test it seems to work.
Finally, for something like this you should use an immediately invoked function or you're sticking all your variables into the global context.
So putting it all together you get something like this:
(function() {
var leadStories = document.getElementsByClassName('cnnTransSubHead')
.map(function(el) { return el.innerText } );
var scanForGuests=/[A-Z ].+,[A-Z0-9 ].+:/g;
var guests = document.body.innerText.match(scanForGuests).join("; ");
alert("Leads: " + leadStories + " Guests: " + guests);
})();
Over 1 hour on this. This is javascript code inside my index.php file.
function dostuff()
{
var thepath = document.location.search.substring(1);
alert('the path is ' + thepath + " (that's the full path)");
alert(thepath);
// TRIED THESE ALL -- NONE OF THEM WORK.
//var pathLen = String.length("thepath");
//var pathLen = String.length(thepath);
//var pathLen = thepath.length();
var pathLen = String.length(document.location.search.substring(1));
alert('pathLen is ' + pathLen);
}
The symptom: the first 2 alert boxes appear no problem and both show 'thepath' has a valid pathname in it, and it is the correct, expected path too.
But no matter what I try -- see the 4 different attempts, tried one at a time -- the final alert() box NEVER shows up.
Why is alert('pathLen is ' + pathLen) not showing up?
(The other thing is -- I'm using XDEBUG and xampp and Netbeans and the debugger will not let me put a breakpoint in this javascript code, so I can't even step into it to see what's happening, hence the use of the alert()'s in the code. I know the XDEBUG debugger I'm using in Netbeans works -- I've been using it all night to debug PHP code in a different.PHP file. When I set a breakpoint though in any Javascript code, a 'broken breakpoint' icon appears and I cannot find what that means in Netbeans documentation.)
I've never seen that syntax before. You might want to try:
var pathLen = thepath.length;
(You'd be best off debugging with Firebug)
var pathLen = thepath.length;
Length is a property of the string, not a function, so no need for the ().
The length is a property of your string rather than a method.
You should be able to access it via the following:
var pathLen = thepath.length;
When you say the alert box never shows up do you mean it never appears at all? If you're using FF you can open the error console from the Tools menu and clear it then refresh your page. It should highlight any JS errors you have in your code. That's the only reason I know of that the alert wouldn't show at all. (I don't think there is a class method for String.length() which is probably where the error is coming from.)
As for XDebug, as far as I know it's a PHP debugger only I don't think it can debug JS.
pathLen.length
No (). length is a property; if you add the (), it tries to use the value of the property as a function to call, resulting in an exception.