JavaScript – Replace all commas in a string [duplicate]

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it. The best way is to use regular expression with g (global) flag. var myStr=”this,is,a,test”; var newStr = myStr.replace(/,/g, ‘-‘); console.log( newStr ); // “this-is-a-test” Still have issues? It is important to note, that regular expressions … Read more

Replace a string in a file with nodejs

You could use simple regex: var result = fileAsString.replace(/string to be replaced/g, ‘replacement’); So… var fs = require(‘fs’) fs.readFile(someFile, ‘utf8’, function (err,data) { if (err) { return console.log(err); } var result = data.replace(/string to be replaced/g, ‘replacement’); fs.writeFile(someFile, result, ‘utf8’, function (err) { if (err) return console.log(err); }); });

Convert clickable anchor tags to plain text in html document

You should be using DOM to parse HTML, not regular expressions… Edit: Updated code to do simple regex parsing on the href attribute value. Edit #2: Made the loop regressive so it can handle multiple replacements. $content=” <p><a href=”http://www.website.com”>This is a text link</a></p> <a href=”http://sitename.com/#foo”>bah</a> <a href=”#foo”>I wont change</a> “; $dom = new DOMDocument(); $dom->loadHTML($content); … Read more

Replacing escape characters from JSON

I have found that the easiest and best way to remove all escape characters from your JSON string, is to pass the string into Regex.Unescape() method. This method returns a new string with no ecapes, even \n \t etc, are removed. See this MSDN article for more details: Regex.Unescape Method (String) (System.Text.RegularExpressions)