JS replacing all occurrences of string using variable [duplicate]

The RegExp constructor takes a string and creates a regular expression out of it. function name(str,replaceWhat,replaceTo){ var re = new RegExp(replaceWhat, ‘g’); return str.replace(re,replaceTo); } If replaceWhat might contain characters that are special in regular expressions, you can do: function name(str,replaceWhat,replaceTo){ replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, ‘\\$&’); var re = new RegExp(replaceWhat, ‘g’); return str.replace(re,replaceTo); } See … Read more

How to insert HTML with a chrome extension?

Here you can research how to create an extension and download the sample manifest.json. Content Scripts can be used to run js/css matching certain urls. manifest.json { “name”: “Append Test Text”, “description”: “Add test123 to body”, “version”: “1.0”, “permissions”: [ “activeTab” ], “content_scripts”: [ { “matches”: [“http://*/*”], “js”: [“content-script.js”] } ], “browser_action”: { “default_title”: “Append … Read more

Bootstrap woff2 font not getting loaded correctly

Since you put a asp.net-mvc tag on your post, I’m giving you IIS configuration solution for you. Chrome doesn’t consume woff and throws 404 error when your web server isn’t configured with MIME type ‘woff’ or ‘woff2’. You need to add IIS a MIME-TYPE for woff2. You can configure it in web.xml. <system.webServer> <staticContent> <remove … Read more

How do you remove an event listener that uses “this” in TypeScript?

First, JavaScript and TypeScript behave the exact same way even if you write like that: theElement.addEventListener(“click”, onClick); Second, this is how you can retain a reference to an anonymous function: var f = (event) => this.onClick(event); theElement.addEventListener(“click”, f); // later theElement.removeEventListener(“click”, f); If you’re dealing with event listeners, there’s a useful pattern for your class … Read more

Printing a web page using just url and without opening new window?

You can do this using a hidden iFrame (I’m using jquery for the example): function loadOtherPage() { $(“<iframe>”) // create a new iframe element .hide() // make it invisible .attr(“src”, “/url/to/page/to/print”) // point the iframe to the page you want to print .appendTo(“body”); // add iframe to the DOM to cause it to load the … Read more

True or better Random numbers with Javascript [duplicate]

Assuming you’re not just seeing patterns where there aren’t any, try a Mersenee Twister (Wikipedia article here). There are various implementations like this one on github. Similar SO question: Seedable JavaScript random number generator If you want something closer to truly random, then consider using the random.org API to get truly random numbers, although I … Read more