Ten short and practical JavaScript code snippets are highly recommended

  • 2021-07-09 06:40:23
  • OfStack

JavaScript is becoming more and more popular, and it has become the first choice for front-end development. With NodeJS based on JavaScript language, we can also develop high-performance back-end services, and even I see JavaScript appearing in the field of hardware programming. JavaScript is evolving into a versatile development language.

But it is not easy to make good use of JavaScript. In addition to mastering its syntax and knowing how to write high-quality code, You also need to know how to solve the requirements scenarios that you will encounter in almost every project. For example, judging dates, highlighting text, limiting the number of characters, etc. There are many third-party libraries that can solve these problems, but these libraries may not only be created to solve this problem, which means that you need to introduce a lot of irrelevant code, which will make your whole system bloated and affect the performance of the system. My approach is to collect and use the common JavaScript code snippets and use them first when needed. Here are 10 pieces of practical JavaScript code I have collected, from which you can create more powerful JS plug-ins or functions.

1. Determine whether the date is valid
The date function in JavaScript is too simple to meet the needs of analyzing and judging different date formats in real projects. JQuery also has a number of third-party libraries to make date-dependent processing simple, but sometimes you may only need a very simple function instead of introducing a huge third-party library. At this point, you can use the following date validation code, which allows you to customize the date format and validate the date.


 function isValidDate(value, userFormat) {

 // Set default format if format is not provided
 userFormat = userFormat || 'mm/dd/yyyy';

 // Find custom delimiter by excluding
 // month, day and year characters
 var delimiter = /[^mdy]/.exec(userFormat)[0];

 // Create an array with month, day and year
 // so we know the format order by index
 var theFormat = userFormat.split(delimiter);

 // Create array from user date
 var theDate = value.split(delimiter);

 function isDate(date, format) {
 var m, d, y, i = 0, len = format.length, f;
 for (i; i < len; i++) {
 f = format[i];
 if (/m/.test(f)) m = date[i];
 if (/d/.test(f)) d = date[i];
 if (/y/.test(f)) y = date[i];
 }
 return (
 m > 0 && m < 13 &&
 y && y.length === 4 &&
 d > 0 &&
 // Check if it's a valid day of the month
 d <= (new Date(y, m, 0)).getDate()
 );
 }

 return isDate(theDate, theFormat);
} 

Usage:
The following call returns false because there are no 31 days in November
isValidDate('dd-mm-yyyy', '31/11/2012')

2. Get the maximum width or height of a set of elements
The following function is very useful for developers who need dynamic typesetting.


 var getMaxHeight = function ($elms) {
 var maxHeight = 0;
 $elms.each(function () {
 // In some cases you may want to use outerHeight() instead
 var height = $(this).height();
 if (height > maxHeight) {
  maxHeight = height;
 }
 });
 return maxHeight;
}; 

Usage:
$(elements).height( getMaxHeight($(elements)) );

3. Highlight text
There are many third-party libraries of JQuery that can realize the function of highlighting text, but I prefer to use the following short JavaScript code to realize this function, which is very short, can be flexibly modified according to my needs, and can define the highlighting style by myself. The following two functions can help you create your own text highlighting plug-in.


 function highlight(text, words, tag) {

 // Default tag if no tag is provided
 tag = tag || 'span';

 var i, len = words.length, re;
 for (i = 0; i < len; i++) {
 // Global regex to highlight all matches
 re = new RegExp(words[i], 'g');
 if (re.test(text)) {
  text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');
 }
 }

 return text;
} 

You will also need to unhighlight the function:


 function unhighlight(text, tag) {
 // Default tag if no tag is provided
 tag = tag || 'span';
 var re = new RegExp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g');
 return text.replace(re, '');
} 

Usage:


 $('p').html( highlight(
 $('p').html(), // the text
 ['foo', 'bar', 'baz', 'hello world'], // list of words or phrases to highlight
 'strong' // custom tag
)); 

4. Text dynamic effect
Sometimes you want to add movement to your paragraph, so that every word in it can move. You can use the following jQuery plug-in code to achieve this effect. Of course, you need to combine an CSS3 transition style to achieve better results.


 $.fn.animateText = function(delay, klass) {

 var text = this.text();
 var letters = text.split('');

 return this.each(function(){
 var $this = $(this);
 $this.html(text.replace(/./g, '<span class="letter">$&</span>'));
 $this.find('span.letter').each(function(i, el){
  setTimeout(function(){ $(el).addClass(klass); }, delay * i);
 });
 });

}; 

Usage:
$('p').animateText(15, 'foo');

5. Hide elements one by one
The following jQuery plug-in can hide 1 group of elements one by one according to the step size (interval time) you set. It can be used in reloading list elements to achieve good results.


 $.fn.fadeAll = function (ops) {
 var o = $.extend({
 delay: 500, // delay between elements
 speed: 500, // animation speed
 ease: 'swing' // other require easing plugin
 }, ops);
 var $el = this;
 for (var i=0, d=0, l=$el.length; i<l; i++, d+=o.delay) {
 $el.eq(i).delay(d).fadeIn(o.speed, o.ease);
 }
 return $el;
} 

Usage:
$(elements).fadeAll({ delay: 300, speed: 300 });

6. Limit the number of words in the text
The following script allows you to intercept text according to a given character length. If the text is intercepted, it will be automatically followed by an ellipsis.


 function excerpt(str, nwords) {
 var words = str.split(' ');
 words.splice(nwords, words.length-1);
 return words.join(' ') +
 (words.length !== str.split(' ').length ? ' … ' : '');
} 

7. Judge the current adaptation degree in the corresponding layout
At present, many designs have adopted responsive layout to adapt the display of websites or applications on different devices. You often need to determine which screen fit you are currently in in your code.


 function isBreakPoint(bp) {
 // The breakpoints that you set in your css
 var bps = [320, 480, 768, 1024];
 var w = $(window).width();
 var min, max;
 for (var i = 0, l = bps.length; i < l; i++) {
 if (bps[i] === bp) {
  min = bps[i-1] || 0;
  max = bps[i];
  break;
 }
 }
 return w > min && w <= max;
} 

Usage:


 if ( isBreakPoint(320) ) {
 // breakpoint at 320 or less
}
if ( isBreakPoint(480) ) {
 // breakpoint between 320 and 480
}
 …  

8. Global Counting
In some games or advertising scenarios, you need to record the number of times a user clicks a button on the current page. At this time, you can use jQuery's. data () function to handle it:


 var getMaxHeight = function ($elms) {
 var maxHeight = 0;
 $elms.each(function () {
 // In some cases you may want to use outerHeight() instead
 var height = $(this).height();
 if (height > maxHeight) {
  maxHeight = height;
 }
 });
 return maxHeight;
}; 
0

9. Embedding Youku Video


 var getMaxHeight = function ($elms) {
 var maxHeight = 0;
 $elms.each(function () {
 // In some cases you may want to use outerHeight() instead
 var height = $(this).height();
 if (height > maxHeight) {
  maxHeight = height;
 }
 });
 return maxHeight;
}; 
1

Usage:


 var getMaxHeight = function ($elms) {
 var maxHeight = 0;
 $elms.each(function () {
 // In some cases you may want to use outerHeight() instead
 var height = $(this).height();
 if (height > maxHeight) {
  maxHeight = height;
 }
 });
 return maxHeight;
}; 
2

10. Create a dynamic menu or drop-down list
In many scenarios, we need to create menus, drop-down lists or list items dynamically. Below is a section of the most basic code to achieve the above functions, you can according to the actual needs of the corresponding expansion.


 function makeMenu(items, tags) {

 tags = tags || ['ul', 'li']; // default tags
 var parent = tags[0];
 var child = tags[1];

 var item, value = '';
 for (var i = 0, l = items.length; i < l; i++) {
 item = items[i];
 // Separate item and value if value is present
 if (/:/.test(item)) {
  item = items[i].split(':')[0];
  value = items[i].split(':')[1];
 }
 // Wrap the item in tag
 items[i] = '<'+ child +' '+
  (value && 'value="'+value+'"') +'>'+ // add value if present
  item +'</'+ child +'>';
 }

 return '<'+ parent +'>'+ items.join('') +'</'+ parent +'>';
} 

Usage:


 var getMaxHeight = function ($elms) {
 var maxHeight = 0;
 $elms.each(function () {
 // In some cases you may want to use outerHeight() instead
 var height = $(this).height();
 if (height > maxHeight) {
  maxHeight = height;
 }
 });
 return maxHeight;
}; 
4

The above is only a small part of those practical JavaScript code snippets. I also suggest that you pay attention to collecting or writing such basic code snippets at ordinary times. They can be used in many projects or provide more perfect functions through 1 transformation. Using these code snippets will save you a lot of development time.


Related articles: