Why doesn't JSFiddle output results for this code - javascript

I have been using the Firebug javascript console to test short scripts. Several people have suggested using JSFiddle instead. The problem is I can't seem to figure out how to do this. I enter my code in the js panel and hit run but nothing happens. I am assuming something should output to results? I tried different settings, reading the JSFiddle documentation, reading other questions posted on Stackoverflow, but I can't figure it out. It seems like it should be so simple. Maybe it only works if I call it from HTML? http://jsfiddle.net/nngrey/QgxCn/ (I had to include my code to reference the link to JSFiddle.)
function Palindrome(str) {
str = str.split("");
for (var i = 0; i < str.length; i++) {
if (str[i] === " ") {
str.splice(i, 1);
}
}
revStr = str.reverse().join("");
str = str.join("");
if (revStr === str) {
return true;
} else {
return false;
}
return str;
}
str = "dont nod";
Palindrome(str);

You can use this jsFiddle to output stuff with console.log. Same idea as alert(), but without a popup you have to close. Thanks to Wayne Koort.
http://jsfiddle.net/TEHLb/
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function (text) {
$("#console-log").append($(consoleLine).html(text));
}
};
var myVar = "foo";
console.log('Your variable has the value ' + myVar);

Without any html to display your answer you can alert it to see the results.
function Palindrome(str) {
str = str.split("");
for (var i = 0; i < str.length; i++) {
if (str[i] === " ") {
str.splice(i, 1);
}
}
revStr = str.reverse().join("");
str = str.join("");
if (revStr === str) {
return true;
} else {
return false;
}
return str;
}
str = "dont nod";
alert(Palindrome(str));

you need alert(Palindrome(str));
try this demo

Related

Alternate cases in textbox Javascript

I want to make a piece of code that alternates the case of text that the user inputs. Currently, my code looks like this:
var num;
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}
$('input, textarea').onkeyup(function () {
prev = true;
for (num = 0; num < this.length; num += 2)
{
this.substr(num).val(toTitleCase(this.substr(num)));
}
});
The problem is that it doesn't work (as in nothing changes). I tried making it a Chrome extension but it doesn't change the case. Is it my way of testing the code that's weird or does the code have a bug?
Try this. Simple code. Codepen Link
$('input, textarea').keyup(function () {
var value = $(this).val();
var altText = '';
for (num = 0; num < value.length; num ++)
{
if(num%2==0)
altText += value[num].toUpperCase();
else
altText += value[num].toLowerCase();
}
$(this).val(altText);
});
Below code should work
var num;
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}
$('input, textarea').keyup(function () {
var value = $(this).val();
var char = value.slice(-1);
if(value.length%2){
var str2 = value.slice(0, -1) + toTitleCase(char);
$(this).val(str2);
}
});

unescape not working in profanity filter

I am trying to make a profanity filter with javascript. I was successful but when I encode the bad words I can't get it
to work. I have been working on this for two days straight.
I have tried to unescape the code in a variable and then use the variable when matching. I have tried unescaping in the
match code too. I have tried mixing in document.write and everything else I can think of.
My original functioning code:
var badwords = /fck|psssy|ssshole/i;
Baddata1 = FirstName.value;
Baddata2 = LastName.value;
if (Baddata1.match(badwords))
{
checker();
FirstName.focus();
return false;
}
if (Baddata2.match(badwords))
{
checker();
LastName.focus();
return false;
}
function checker()
{
window.alert("Please Remove Bad Words");
}
You can reverse the string by subtracting char codes from 0xffff to encode, then, reverse it back again to get clear text. Use "new RegExp" to construct:
var encstr = "ン゙ロテム゙フヒニテネミヘロ"; // "bad|nasty|word" put through reverse() function
var badwords = new RegExp(reverse(encstr), "i");
var Baddata1 = "bad";
var Baddata2 = "LastName";
function reverse(str) {
var sout = "", ix;
if (!str) {
return "";
}
for (ix = 0; ix < str.length; ++ix) {
sout += String.fromCharCode(0xffff - str.charCodeAt(ix));
}
return sout;
}
if (Baddata1.match(badwords))
{
checker();
FirstName.focus();
return false;
}
if (Baddata2.match(badwords))
{
checker();
LastName.focus();
return false;
}
function checker()
{
window.alert("Please Remove Bad Words");
}
Working jsfiddle here.
If you don't like using high character codes, I can easily substitute various encoding functions which don't, though this one is the most compact.
Edit: To get the reversed string, either use a JS debugger to call reverse, or, add temporary code like this:
console.log(reverse("bad|nasty|word"));
This works because reverse(reverse(string1)) === string1. reverse undoes itself.
You could also keep a list of words in a separate script, and use JS string join passed to reverse to make the list, for example:
var wordlist = ["bad", "nasty", "word"];
var joined = wordlist.join("|");
console.log('var encstr = "' + reverse(joined) + '"');
Once you've copied the string from the debug console and pasted it, the separate script could easily check that it's correct:
var encstr = "ン゙ロテム゙フヒニテネミヘロ";
alert("encstr " + (reverse(encstr) === joined ? "matches" : "does NOT match") + " original");
Edit 2: If you don't want to use high char codes that fall into international ranges, just use an encoding like base64, or this simple set:
function encodeStr(str) {
var sout = "", ix;
if (!str) {
return "";
}
for (ix = 0; ix < str.length; ++ix) {
if (sout.length)
sout += ",";
sout += str.charCodeAt(ix).toString(16);
}
return sout;
}
function decodeStr(str) {
var sout = "", narr, ix;
if (!str) {
return "";
}
narr = str.split(",");
for (ix = 0; ix < narr.length; ++ix) {
sout += String.fromCharCode(parseInt(narr[ix], 16));
}
return sout;
}
// Using encodeStr on "bad|nasty|word" makes this:
var encstr = "62,61,64,7c,6e,61,73,74,79,7c,77,6f,72,64";
var badwords = new RegExp(decodeStr(encstr), "i");

String modification issue in JS

I have a string like "word_count". How can I transform it to "WordCount" in an elegant way using JavaScript? My decision seems too complicated to me. I'll be very grateful for your help.
function titleCase(str)
{
return str.split("_")
.map(function (s) { return s.charAt(0).toUpperCase() + s.slice(1); })
.join("");
}
Take a look at this. I don't want to just copy paste everything here, but it seems to be just what you're looking for.
Here is the function modified to fit your request:
String.prototype.toCamel = function(){
return this.replace(/((^|\_)[a-z])/g, function($1){
return $1.toUpperCase().replace('_','');});
};
And here it is in action.
You can use a regular expression to match either a letter at the start of the string or a letter after an underscore, and use a callback to turn the letter into uppercase:
s = s.replace(/(?:^|_)([a-z])/g, function(m, g){
return g.toUpperCase();
});
Demo: http://jsfiddle.net/Guffa/ByU6P/
Simple, like this:
var string = "word_count".split("_");
for(var i = 0; i<string.length;i++) {
string[i] = string[i].charAt(0).toUpperCase() + string[i].substr(1);
}
var myNiceString = string.join();
If you want to add it to the String object, you can do this:
String.prototype.titleCase = function() {
var split = this.split("_");
for(var i = 0; i<split.length;i++) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].substr(1);
}
return split.join("");
}
You'd call it like "word_count".titleCase();
You can use a function like the following:
var Pascalize = function(word) {
var x = word;
result = '';
if(-1 != word.indexOf('_')) {
x = word.split('_');
for(var i=0;i<x.length;i++) {
result += x[i].substr(0, 1).toUpperCase() + x[i].substr(1);
}
}
if('' == result) { result = word; }
return result;
};
var PascalCaseString = Pascalize("this_is_a_test");
// PascalCaseString value is now 'ThisIsATest'
Here's a working example
var str = "word_count";
var re = /\b(.)([^_]+)_(.)/;
var newWord = str.replace(re, function(m,f,t,l){ return f.toUpperCase() + t + l.toUpperCase();})
console.log(newWord);
Using jQuery, you could do the following:
var result = '';
$.each('word_count'.split('_'), function(idx,elem){
result = result + elem.substr(0,1).toUpperCase() + elem.substr(1);
});
New version (works with any amount of _):
function fixString(sString) {
var aWords = sString.split("_"),
sResults = "";
for (var i in aWords)
sResults += aWords[i].charAt(0).toUpperCase() + aWords[i].slice(1);
return sResults;
}
The compressed form:
function fixString(c){var d=c.split("_"),a="";for(var b in d){a+=d[b].charAt(0).toUpperCase()+d[b].slice(1)}return a};
Old:
function fixString(sString) {
return sString.replace(/(.*)_(.*)/, function(sWhole, $1, $2, sWTF) {
return ucfirst($1) + ucfirst($2);
} )
function ucfirst (str) {
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
}
... or the compressed version:
function fixString(b){return b.replace(/(.*)_(.*)/,function(e,c,f,d){return a(c)+a(f)});function a(d){d+="";var c=d.charAt(0).toUpperCase();return c+d.substr(1)}};
Of course, this is used like fixString("word_count") which results in your desired WordCount.
I've looked at all the answer and none did precisely what I wanted. I wanted an idempotent function which converted to camelCase (not PascalCase) and I liked the String prototype extension approach (although obviously this isn't always the best medicine).
Anyway, here's where I ended up:
String.prototype.camelize = function(){
var pascalCase = this.replace(/((^|\_)[a-z])/g, function($1){
return $1.toUpperCase().replace('_','');
});
return pascalCase.charAt(0).toLowerCase() + this.slice(1);
};
var aStringLike = "word_count";
// magic follows
aStringLike = "WordCount";

How to replace only first sequential occurences (fuzzymatch)?

I'm trying to write "fuzzy" match and I can't find a way to solve this problem:
Data in: makrusakkk, query: mrk, expected result: <b>m</b>ak<b>r</b>usa<b>k</b>kk.
RegExp: "makrusakkk".match(/(m).*?(r).*?(k)/i) returns ["makrusak", "m", "r", "k"].
So the question is: is there a way to get the expected result using RegExp?
I think using regular expression for such problem makes things just more complicated. The following string and loop based solution would lead to the result:
function fuzzySearch(query, input) {
var inds = patternMatches(query, input);
if(!inds) return input;
var result = input;
for(var i = inds.length - 1; i >= 0; i--) {
var index = inds[i];
result = result.substr(0,index) +
"<b>" + result[index] + "</b>" +
result.substr(index+1);
}
return result;
}
function patternMatches(query, input) {
if(query.length <= 0) {
return [];
} else if(query.length == 1) {
if(input[0] == query[0]) return [0];
else return [];
} else {
if(input[0] != query[0])
return false;
var inds = [0];
for(var i = 1; i < query.length; i++) {
var foundInd = input.indexOf(query[i], inds[i-1]);
if(foundInd < 0) {
return [];
} else {
inds.push(foundInd);
}
}
return inds;
}
}
var input = "makrusakkksd";
var query = "mrk";
console.log(fuzzySearch(query, input));
console.log(patternMatches(query, input));
Here's a live demo too: http://jsfiddle.net/sinairv/T2MF4/
Here you will need for:
function search_for_it(txt, arr){
for(i=0;i<arr.length;i++){
var reg = new RegExp(arr[i], "i");
txt = txt.replace(reg, "<b>"+arr[i]+"</b>");
}
return txt;
}
search_for_it("makrusakkk", ["m","r","k"]);
//return "<b>m</b>a<b>k</b><b>r</b>usakkk"
PS: Your expected result is incorrect. There is a k after the first a.
is there a way to get an expected result using RegExp?
There is.
"makrusakkk".replace(/(m)(.*?)(r)(.*?)(k)/i, '<b>$1</b>$2<b>$3</b>$4<b>$5</b>'​​​​​​​)
I feel vaguely dirty for this, but...regardless; here's one way to do it:
$('#s').keyup(
function(e) {
var w = e.which;
if (w == 8 || w == 46) {
return false;
}
var listElems = $('ul:first li'),
search = $(this).val().replace(/w+/g, ''),
r = search.split(''),
rString = [];
$.each(r, function(i, v) {
rString.push('(' + v + ')');
});
var reg = new RegExp(rString.join('(\\d|\\D)*'), 'gi');
listElems.each(
function() {
if (!$(this).attr('data-origtext')) {
$(this).attr('data-origtext', $(this).text());
}
$(this).html($(this).attr('data-origtext').replace(reg, '<b>$&</b>'));
});
});​
JS Fiddle demo.
It could, almost certainly, benefit from quite some simplification though.
References:
attr().
:first selector.
join().
keyup().
push().
RegExp().
replace().
split().
text().
val().

javascript abstract console logging

I want to make a function, like this.
For example:
function Logger() {
this.log = function(msg) {
console.log(msg);
}
}
And I want to use it in functions/modules etc, and that all works fine.
But the default console in my browser normally give the fileName + lineNumber.
Now when I abstract this functionality, the fileName and lineNumber is not where I put my instance.log(). Because it will say from where the console.log is being called, not the function itself.
So my question:
How can I get the correct information from where I want to use my logger?
Or give me, please, any tips to improve this functionality.
function Logger() {
this.log = console.log.bind(console);
}
I asked about this some time ago: Create shortcut to console.log() in Chrome.
Try using backtrace function like this one :
function printStackTrace() {
var callstack = [];
var isCallstackPopulated = false;
try {
i.dont.exist += 0; //doesn't exist- that's the point
} catch (e) {
if (e.stack) { //Firefox
var lines = e.stack.split('\n');
for (var i = 0, len = lines.length; i & lt; len; i++) {
if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
callstack.push(lines[i]);
}
}
//Remove call to printStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
else if (window.opera & amp; & amp; e.message) { //Opera
var lines = e.message.split('\n');
for (var i = 0, len = lines.length; i & lt; len; i++) {
if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
var entry = lines[i];
//Append next line also since it has the file info
if (lines[i + 1]) {
entry += ' at ' + lines[i + 1];
i++;
}
callstack.push(entry);
}
}
//Remove call to printStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
}
if (!isCallstackPopulated) { //IE and Safari
var currentFunction = arguments.callee.caller;
while (currentFunction) {
var fn = currentFunction.toString();
var fname = fn.substring(fn.indexOf( & amp; quot;
function & amp; quot;) + 8, fn.indexOf('')) || 'anonymous';
callstack.push(fname);
currentFunction = currentFunction.caller;
}
}
output(callstack);
}
function output(arr) {
//Optput however you want
alert(arr.join('\n\n'));
}
Try assigning the function:
(function () {
window.log = (console && console.log
? console.log
: function () {
// Alternative log
});
})();
Later just call log('Message') in your code.

Categories

Resources