Adapt textarea max word plugin - javascript

How would one adapt this jquery plugin so that it counts down from how many words your allowed/you have remaining, instead of counting up to how many your allowed.
www.javascriptkit.com/script/script2/enforceform.shtml
Thanks in advance.

There is also a very simple way to do it without a maxlength attribute. (This example uses 200 as the maximum characters).
$("#YourTextareaId").keyup(function () {
var i = $("#YourTextareaId").val().length;
$('#IdOfCountdownDisplay').val(''+200-i+'');
A nice thing to remember when coding, is that a simple equation can get rid of a whole lot of complicated code.

open the maxlength.js file and put this
$field.data('$statusdiv').css('color', '').html( $field.data('maxsize') - $field.val().length )
instead of this:
$field.data('$statusdiv').css('color', '').html($field.val().length)

Related

Find and replace regex JavaScript

I know this is a super easy question, but I can't seem to wrap my head about it. I've got a bunch of URLs in varying languages such as:
www.myurl.com?lang=spa
www.myurl.com?lang=deu
www.myurl.com?lang=por
I need to create buttons to quickly switch from any language extension (spa, por, deu, rus, ukr, etc) to another language. I have the following code so far:
var url = window.location.toString();
window.location = url.replace(/lang=xxx/, 'lang=deu');
I just can't figure out the 3-character wildcard character. I know that I need to do some sort of regular expression or something, I'm just not sure how to go about it. Any help?
Thanks in advance
You can use
([&?]lang=)\w+
This will work with urls like www.myurl.com?foo=bar&lang=por&bar=foo too.
Instead of lang=deu, you'll have to replace with $1deu.
Try ... or .{3} or \w{3} or even [a-z]{3}, depending on how specific you want to be.
var s = 'www.myurl.com?lang=spa';
s.replace(/lang=[a-z]{3}/, 'lang=deu');
// => "www.myurl.com?lang=deu"
Here's a railroad diagram of the above example:
Use /lang=[a-z][3}/, here's an example:
/lang=[a-z]{3}/
Debuggex Demo

How to Split many Strings with Jquery

Let's say I have a bunch of strings which I get from user input. Each strings starts with a new line like the following example:
gordon:davis
harley:vona
empir:domen
furno:shyko
I would like to write a function in jQuery which loads the user data from the form and splits each row's sting. However I would ONLY need the first part of the strings, like:
gordon
harley
empir
furno
Is there any simple solution for this?
I have found something called: $.each(split) but I didn't get it work.
I'm sorry I'm a really newbie in Jquery, I hope you guys can help me out! Thanks in advance!
Use String.prototype.split method.
"gordon:davis".split(":") will return ["gordon","davis"]
Based on this, using Array.prototype.map or a JQuery version :
var strings = ["gordon:davis", "harley:vona"];
var splitStrings = strings.map(function (string) {
return string.split(":")[0];
});

Making bulk JavaScript replace more efficient

I have some JavaScript which replaces smiley symbols with their corresponding images in my blog.
So symbols like :) or :( are replaced by proper <img> tags.
Currently there are around 50 smiley symbols that can be used. But in any page only a few of them will be used obviously.
The script has lines of the form element.replace(smileyRegex, <imgTags>) for each smiley.
The problem is that, due to a large number of these regex matching lines, the script causes a slight delay after the page is loaded.
I'm thinking of the following method to make this more efficient: To call replace with a large regex which matches all smiley symbols as first argument, and a function which chooses proper image from an array as the second argument.
Will this usage be more efficient than a number of separate replace calls that may or may not match?
Having one regex match all occurences of smileys would be a lot more efficient. That is because it would only be one iteration through the source, instead of one interation per smiley. Then have an appropriate hashtable / object with smiley -> img src would be an efficient lookup:
var smileyImgMap = {
":)" : "happysmiley.png",
":(" : "sadsmiley.png"
};
Then use it like this:
var smileyImg = smileyImgMap[":)"];
I think you get the idea.
I wrote this jsperf to test the two concepts. It probably needs more representative data put in it for what type of source data you're searching through, how many different things you're looking for and how often you are likely to find a match. You can fill those into the basic framework in the jsperf and then look at it in different browsers.
The regex w/callback option looks basically like this:
var replaceLookup = {aa: "--", bb: "++", cc: "**"};
var result = sourceStr.replace(/aa|bb|cc/g, function(str, p1, p2, offset, s)
{
return(replaceLookup[str]);
});
Almost any "which is more efficient" question is going to get an answer like "it depends". What you're proposing certainly sounds promising but you really should just benchmark on a few different browsers and be sure.
Another solution would be to render the page as is, and then asynchronously go through each of the 50 smileys and run the regexps one at a time. It would certain take more time, but your user wouldn't perceive the delay (since the page is already rendered).
One way to speed it up is to place all smileys in one image and use it as a css sprite.
.smily1 {background:url('/images/allSmilyImage.png') 0px 0px}
.smily2 {background:url('/images/allSmilyImage.png') 0px 50px}
.smily3 {background:url('/images/allSmilyImage.png') 50px 100px}
...
Specify the smileys image position in a css file then use the hash mapping as #jishi suggested for mapping the css styles for the corresponding smily.
var smileyClassMap = {
":)" : "smily1",
":(" : "smily2",
":P" : "smily3"
};
Replace the text smileys with a <span class="smily1" style="display:block" /> tag or similar

How to find document element by regexp?

for example I have many input elements with name "test_(1...100)". I want to find all of them.
I just so happened to have had the exact same problem, this is how I solved it:
var divs=document.getElementsByTagName("div");
var re = /test_[\d]+/i;
for (thediv in divs) {
if (divs[thediv].id != null && divs[thediv].id.match(re)) {
//your stuff here
}
}
And as slhck pointed out, to make the chance of getting an answer bigger you should start accepting some answers to your questions. This is done by using the Green checkmark next to every answer.
Use RegularExpressions. An online tool might help.
The expression you need will be something like:
test_[\d]+
If you are using jQuery, then you can use .filter() with a function:
$('input').filter(function(){
return this.name.match(/^test/);
}).css({background: 'red'});
See DEMO.
If you are not using any library that would help you with that then you have to iterate over every input element that you find and match its name with your regex on every iteration.

JAVASCRIPT - dateobj.getTime for a UID - Is the length not fixed?

I'm using the following 2 lines of JS to create a UID:
var UID = dateobj.getTime();
UID = String(UID).substr(4);
It appears that sometimes it generates a number like:
564929300
other times like:
56492930
Problem is the length isn't consistent which is messing things up. Any ideas how that's possible and if there is a way to fix this or a better way to make a UID with JS?
Thanks
I like doing Math.random().toString(36).substr(2,9)
There one implementation here:
http://blog.shkedy.com/2007/01/createing-guids-with-client-side.html
Here it is in action: http://jsfiddle.net/7sXL6/
I threw together a smaller version of it: http://jsfiddle.net/7sXL6/4/

Categories

Resources