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);
}
});
Related
EDITING to include solution based on Brian Hedlund's suggestion. Solution is at bottom.
I am getting this error in the console log
Syntax error, unrecognized expression: <h1>
This is the line generating the error
var substring = txt.find(tag).eq(i).text();
Sample data and code are below.
Why does that line throw that error and how can it be fixed?
I have verified that the function _mpactIdeation_countOccurrences() does execute properly as well as all lines in the function mpactIdeation_getTagContentsKeyphrase() above the line
var substring = txt.find(tag).eq(i).text();
Thanks for your time and consideration,
Tim
Sample Data:
The variable tag holds "<h1>".
The variable kp holds "fish".
The variable txt holds "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>".
Code:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
txt = jQuery(txt);
for (i = 0; i < tagcount; i++) {
tag = this._mpactIdeation_escapeRegExp(tag);
var substring = txt.find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
this._mpactIdeation_countOccurrences = function( string, subString, allowOverlapping ) {
try {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var num = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++num;
pos += step;
} else break;
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
SOLUTION:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
txt = jQuery(txt);
tag = this._mpactIdeation_tagToText(tag);
for (i = 0; i < tagcount; i++) {
var substring = txt.find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
this._mpactIdeation_countOccurrences = function( string, subString, allowOverlapping ) {
try {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var num = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++num;
console.log( "countOccurrences FOUND: " + subString + " INCREMENT");
pos += step;
} else break;
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
this._mpactIdeation_tagToText = function(tag) {
try {
return tag = tag.replace(/[<>]/g, '');
} catch(e) {
console.log(e);
return false;
}
}
The correct find syntax is find('h1'), not find('<h1>')
This will fix your error, but not find your h1. find looks for descendants of the searched target, and since your txt has no root node, the intended target h1 is not a descendant, but a sibling. .siblings('h1') would do the trick.
I'm having a problem when trying to multiply the totalPallets by the price-per-pallet ($25) and then showing that in the productSubTotal box. With the code as it is right now, the quatity total shows but when I try to get the price result, it doesn't show the operation. Also, if I try changing anythung from the code, the whole thing breaks down. I'll be thankful if anyone could help me. Thanks
// UTILITY FUNCTIONS
function IsNumeric(n) {
return !isNaN(n);
}
function calcTotalPallets() {
var totalPallets = 0;
$(".num-pallets-input").each(function() {
var thisValue = parseInt($(this).val());
if ( (IsNumeric(thisValue)) && (thisValue != '') ) {
totalPallets += parseInt(thisValue);
};
});
$("#quantitytotal").val(totalPallets);
}
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".totalprice").each(function() {
var valString = parseInt(totalPallets) * multiplier;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
};
// "The Math" is performed pretty much whenever anything happens in the quanity inputs
$('.num-pallets-input').bind("focus blur change keyup", function(){
// Caching the selector for efficiency
var $el = $(this);
// Grab the new quantity the user entered
var numPallets = CleanNumber($el.val());
var totalPallets = CleanNumber($el.val());
var prodSubTotal = CleanNumber($el.val());
// Find the pricing
var multiplier = $el
.parent().parent()
.find("td.price-per-pallet span")
.text();
};
// Calcuate the overal totals
calcProdSubTotal();
calcTotalPallets();
});
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
amount = "$" + minus + n;
return amount;
}
});
I am trying to make a function in javascript that would expand/split a string with dashes and show the process ( line by line ) using recursion.
for example, the string "anna" would become:
expand("anna") = expand("an")+"---"+expand("na") ->
"a"+"---"+"n"+"---"+"n"+"---"+"a"
and the desired output would be:
anna
an---na
a---n---n---a
I have achieved doing the following so far (I know it might not be the solution I am looking):
expand("anna") = an+"---"+expand("na")
= an+"---"+n+"---"+expand("a");
= an+"---"+n+"---+"a"
the output I am getting is:
an---n---a
I can't seem to concatenate the head though to do the first example.
My javascript function of expand is as follows:
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return word.substr(0,mid) + " " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));
I would need some tips to do this, otherwise (if it's the wrong stackexchange forum), please guide me where to post it.
this is my crazy attempt
var Word = function(str) {
this.isSplitable = function() {
return str.length > 1;
}
this.split = function() {
var p = Math.floor(str.length / 2);
return [
new Word(str.substr(0,p)),
new Word(str.substr(p,p+1))
];
}
this.toString = function() {
return str;
}
}
var expand = function(words) {
var nwords = [];
var do_recur = false;
words.forEach(function(word){
if(word.isSplitable()) {
var splitted = word.split();
nwords.push(splitted[0]);
nwords.push(splitted[1]);
do_recur = true;
}else{
nwords.push(word);
}
});
var result = [];
nwords.forEach(function(word){
result.push( word.toString() );
});
var result = result.join("--") + "<br/>";
if(do_recur) {
return result + expand(nwords);
}else{
return "";
}
}
document.write( expand([new Word("anna")]) );
This is what you need
expand = function(word) {
return [].map.call(word, function(x) {return x+'---'}).join('')
};
The joy of functional programming.
And with added code to deal with last character:
function expand(word) {
return [].map.call(word, function(x, idx) {
if (idx < word.length - 1)
return x+'---';
else return x
}).join('')
}
As I said that it is impossible to display the "process" steps of recursion while using recursion, here is a workaround that will output your desired steps:
var levels = [];
function expand(word, level) {
if (typeof level === 'undefined') {
level = 0;
}
if (!levels[level]) {
levels[level] = [];
}
levels[level].push(word);
if (word.length <= 1) {
return word;
} else {
var mid = Math.ceil(word.length/2);
return expand(word.substr(0, mid), level+1) + '---' + expand(word.substr(mid), level+1);
}
}
expand('anna');
for (var i = 0; i < levels.length; i++) {
console.log(levels[i].join('---'));
}
to see all steps the best that I whold do is:
function expand(word) {
if (word.length<=1) {
return word;
} else {
var mid = word.length/2;
var str1 = word.substr(0,mid);
var str2 = word.substr(mid,word.length);
document.write(str1 + "---" + str2 + "<br></br>");
return expand(str1) + "---" + expand(str2);
}
}
document.write(expand("anna"));
You have to return the two parts of the string:
function expand(word) {
output="";
if (word.length<=1) {
output+=word;
return output;
} else
{
var mid = word.length/2;
output+=word.substr(0,mid)+"---"+word.substr(mid)+" \n";//this line will show the steps.
output+=expand(word.substr(0,mid))+"---"+expand(word.substr(mid,word.length-1))+" \n";
return output;
}
}
console.log(expand("anna"));
Edit:
I added the output var and in every loop I concatenate the new output to it.
It should do the trick.
Hope the problem is in your first part. According to your algorithm, you are splitting your string anna in to two parts,
an & na
so you need to expand both parts until the part length is less than or equal to one. so your required function is the below one.
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return expand(word.substr(0,mid)) + " --- " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));
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
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().