Remove all items after an index

Use Array.length to set a new size for an array, which is faster than Array.splice to mutate: var array = [‘mario’,’luigi’,’kong’, 1, 3, 6, 8]; array.length=2; alert(array); // shows “mario,luigi”; Why is it faster? Because .splice has to create a new array containing all the removed items, whereas .length creates nothing and “returns” a number …

Read more

Missing Javascript “.map” file for Underscore.js when loading ASP.NET web page [duplicate]

What you’re experiencing is source mapping. This allows you to debug with readable code in your browser’s developer tools when working with minified JS files. The minified version of Underscore has this line at the end of the file: //# sourceMappingURL=underscore-min.map Your browser’s developers tools will try to download underscore-min.map when encountering this line. If …

Read more

How do I restrict an input to only accept numbers?

Easy way, use type=”number” if it works for your use case: <input type=”number” ng-model=”myText” name=”inputName”> Another easy way: ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the “cookbook” page about forms. Hackish? way, $watch the ng-model in your controller: <input type=”text” ng-model=”myText” name=”inputName”> …

Read more

JavaScript – How do I get the URL of script being called?

From http://feather.elektrum.org/book/src.html: var scripts = document.getElementsByTagName(‘script’); var index = scripts.length – 1; var myScript = scripts[index]; The variable myScript now has the script dom element. You can get the src url by using myScript.src. Note that this needs to execute as part of the initial evaluation of the script. If you want to not pollute …

Read more

Filtering an array with a function that returns a promise

Here is a 2017 elegant solution using async/await : Very straightforward usage: const results = await filter(myArray, async num => { await doAsyncStuff() return num > 2 }) The helper function (copy this into your web page): async function filter(arr, callback) { const fail = Symbol() return (await Promise.all(arr.map(async item => (await callback(item)) ? item …

Read more

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

$(‘div’).attr(‘style’, ”); or $(‘div’).removeAttr(‘style’); (From Andres’s Answer) To make this a little smaller, try this: $(‘div[style]’).removeAttr(‘style’); This should speed it up a little because it checks that the divs have the style attribute. Either way, this might take a little while to process if you have a large amount of divs, so you might want …

Read more