Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, November 30, 2023

ECMAScript 2023 Object.groupBy

ECMAScript 2023, the 14th edition of the language, has some great changes that will make your programming life easier.


Reference

Grouping object by key value using reduce()

Grouping objects by key-value

Thursday, November 23, 2023

How to Create Web Component

As of 2023, the support for web components, alternatively referred to as custom elements, across browsers is exceptionally robust. Now is an opportune moment to embark on the journey of crafting your personalized elements for the web.

Web components, synonymous with custom elements, represent novel HTML elements that you can personally construct. These elements encapsulate a combination of markup, style, and interactive features.

Within the confines of this article, you'll delve into the fundamentals of web components and embark on the creation of a straightforward web component designed to display the current date.

Example


 # A Complete Guide to Regular Expressions

Regular expressions, often referred to as regex or regexp, provide a powerful and flexible way to search, match, and manipulate text. They are widely used in programming, text processing, and data validation. This guide aims to provide a comprehensive overview of regular expressions, including syntax, common patterns, and practical examples.


## Table of Contents

  1. Introduction to Regular Expressions
  2. Basic Syntax and Matching
  3. Metacharacters
  4. Quantifiers
  5. Character Classes
  6. Anchors
  7. Grouping and Capturing
  8. Alternation
  9. Escape Characters
  10. Examples and Use Cases


### 1. Introduction to Regular Expressions

Regular expressions are patterns that describe sets of strings. They are used for pattern matching within strings. A regular expression is composed of ordinary characters and special characters called metacharacters.


### 2. Basic Syntax and Matching

- `.` (dot): Matches any single character except a newline.
- `^`: Anchors the regex at the start of a line.
- `$`: Anchors the regex at the end of a line.

Example:
^Hello$


This regex matches the string "Hello" only if it appears at the beginning of a line.

### 3. Metacharacters

- `*`: Matches zero or more occurrences of the preceding character or group.
- `+`: Matches one or more occurrences of the preceding character or group.
- `?`: Matches zero or one occurrence of the preceding character or group.

Example:
\d+ 

This regex matches one or more digits.

### 4. Quantifiers

- `{n}`: Matches exactly n occurrences of the preceding character or group.
- `{n,}`: Matches n or more occurrences of the preceding character or group.
- `{n,m}`: Matches between n and m occurrences of the preceding character or group.

Example:
\w{3,6}

This regex matches word characters (alphanumeric + underscore) with a length between 3 and 6.

### 5. Character Classes

- `\d`: Matches any digit (0-9).
- `\w`: Matches any word character (alphanumeric + underscore).
- `\s`: Matches any whitespace character (space, tab, newline).

Example:
[A-Za-z]\d{2}

This regex matches an uppercase or lowercase letter followed by two digits.

### 6. Anchors

- `\b`: Word boundary.
- `\B`: Non-word boundary.
- `^` (caret) and `$` (dollar): Match the start and end of a line, respectively.

Example:
\bword\b

This regex matches the word "word" as a whole word.

### 7. Grouping and Capturing

- `()`: Groups characters together.
- `(?:)`: Non-capturing group.

Example:
(\d{3})-(\d{2})


This regex captures a three-digit group, a hyphen, and a two-digit group.

### 8. Alternation

- `|`: Acts like a logical OR.

Example:
cat|dog

This regex matches either "cat" or "dog".

### 9. Escape Characters

- `\`: Escapes a metacharacter, treating it as a literal character.

Example:
\d\.\d

This regex matches a digit followed by a literal dot and another digit.

### 10. Examples and Use Cases

- Email Validation:
  ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

- URL Matching:
  ^(https?|ftp)://[^\s/$.?#].[^\s]*$

- Phone Number Matching:
  ^\+?[1-9]\d{1,14}$

- Extracting Date from Text:
  (\d{4})-(\d{2})-(\d{2})

- HTML Tag Matching:
  <([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>(.*?)</\1>


Remember that while regular expressions are powerful, they can be complex. It's essential to test and validate them thoroughly.

This guide provides a foundation for understanding regular expressions, but there is much more to explore. Practice and experimentation are key to mastering this powerful tool.

Wednesday, November 15, 2023

Get HTML table column values in array using map ()

Developers often find themselves needing to validate HTML table columns values, occasionally getting stuck in loops. Here's a straightforward solution: use the map() function to easily retrieve the values in an array.

SrNo Name City
1 Rakesh Vadodara
2 Anil Ahmedabad
3 Sunil Anand
4 Bharat Udaipur


Wednesday, November 8, 2023

Some Useful APIs

Sharing some valuable APIs that have been instrumental in my projects on this blog for your reference.

(1) LocalStorage API

It lets you store data against the website address in the form of key/value pairs. Local storage is limited to 5 MB.

(2) Clipboard API

This API provides access to the operating system's clipboard. You can use it to build a copy button to copy/paste content.

(3) Geolocation API

This API provides the user's geographical latitudes and longitudes and the accuracy to which it is correct.

(4) History API

This API lets you go back and forth between web pages that are in your session history.

(5) Fetch API

It is a browser API that lets you call REST APIs or GraphQL APIs.

Note: Content published here is sourced from social platforms, and full credit goes to the original author.

Tuesday, September 12, 2023

Extract all URLs from a web page

Here is a quick JavaScript snippet to extract all URLs from a webpage, using Developer Tools. No Browser Extension is required!

Friday, June 9, 2023

Dropdown Menu with Checkbox

    

Friday, May 12, 2023

Push into an Array in JavaScript


let myarray = [1,2,3,4,5]


// Add to the start of an array

Array.unshift(element);

myarray.unshift(100); // output 100,1,2,3,4,5


// Add to the end of an array

Array.push(element);

myarray.push(100); // output 1,2,3,4,5,100



// Add to a specified location

Array.splice(start_position, 0, new_element...);

myarray.splice(2, 0, 100,200); // output 1,2,100,200,3,4,5



// Add with concat method without mutating original array

let newArray = [].concat(element);

let newmyarray = myarray.concat(10,20);


Monday, April 3, 2023

Get week number of month from Date

People struggle a lot when it needs to get a week from a date, here below is a simple example to get the week number of the month from a Date.

Tuesday, November 22, 2022

Javascript Tips and Best Practices

1. Check property exists in an object

The in operator returns the boolean value true/false.
The in operator returns true if a property exists in the object or its prototype chain.

2. String to a number using the plus (+) operator

The unary plus operator (+) is the fastest and preferred way of converting something into a number.

3. Mask numbers using slice and padStart

The slice() method returns selected elements in an array, as a new array. Negative numbers select from the end of the array.
The padStart() method pads the current string with another string until the resulting string reaches the given length. The padding is applied from the start of the current string.

4. Swap two variables

Use destructuring assignment approach because it is short and expressive. Swapping is performed in just one line statement. It works with any data type like numbers, strings, booleans, or objects.

5. Check every element of the array using Array.every

The Array every() method checks whether all the array elements pass the test implemented by the provided function.
It returns true if the function returns true for all elements.
It returns false if the function returns false for one element. When every() finds a false result, it will stop the loop and continue no more which improves the performance. The every() method does not change the original array.

6. Use of nullish coalescing operator with numbers

I have use lot of time || operator for the logical disjunction, but it ends when value is 0 in the variable. So found better way to handle this.

A Nullish value is a value that is either null or undefined.
The Nullish Coalescing Operator (??) is a logical operator that accepts two values and returns the second value if the first one is null or undefined and otherwise returns the first value.

7. Filter Array with only values

Many times we have an issue with array to have empty values and need to handle we write extra code. To avoid it just you have to use filter().

Pass the Boolean to Array.filter as the first argument.

Monday, July 11, 2022

Dropdown list with multi-select checkbox

 

JavaScript
CSS Style
HTML

Wednesday, May 11, 2022

JavaScript - Inheritance of Methods and Properties



Selecting Elements

Selection of the elements using document

  • document.documentElement
  • document.head
  • document.body

Query selection

  • document.querySelector(‘.header’) // only select 1 element
  • document.querySelectorAll(‘.section’) // all element with class section
  • document.getElementById(‘section1’) // you can find element by ID
  • document.getElementsByTagName(‘button’) // all element by tag – this is live collection
  • document.getElementsByClassName(‘btn’) // all element have class btn

Creating and Inserting elements

  • .insertAdjacentHTML // use to insert first in element
  • document.createElement(‘div’) // create DOM in javascript, you can append or insert in your page.
  • .prepend() // add element as first child
  • .append() // add element as last child
  • .before() // add before the element
  • .after() // add after the element
  • .remove() // delete the element

Important to know about Class

const logo = document.querySelector(‘.nav__logo’); // element
  • logo.classList.add(‘a’, ’b’) // add class to element
  • logo.classList.remove(‘a’, ‘b’) // remove class
  • logo.classList.toggle(‘c’) // toggle
  • logo.classList.contains(‘c’) // this will check if class is present in the element or not

Monday, January 3, 2022

Export HTML table to Excel

Code that will export html table to excel

Tuesday, December 14, 2021

Convert Number, String, Float and Format JSON

 1) Convert to String

To quickly convert a number to a string, we can use the concatenation operator (+) plus followed by an empty set of quotation marks "" .

let val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

2) Convert to Number

The opposite can be quickly achieved using the addition operator + .

let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

This may also be used to convert Booleans to numbers, as below:

console.log(+true);  // Return: 1
console.log(+false); // Return: 0

3)Quick Float to Integer

If you want to convert a float to an integer, you can use Math.floor() , Math.ceil() or Math.round() . But there is also a faster way to truncate a float to an integer using |, the bitwise OR operator.

console.log(23.9 | 0);  // Result: 23
console.log(-23.9 | 0); // Result: -23

4)Format JSON Code

Lastly, you may have used JSON.stringify before, but did you realise it can also help indent your JSON for you?
The stringify() method takes two optional parameters: a replacer function, which you can use to filter the JSON that is displayed, and a space value.
The space value takes an integer for the number of spaces you want or a string (such as '\t' to insert tabs), and it can make it a lot easier to read fetched JSON data.

console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'

Monday, December 13, 2021

Get Query Params

window.location object has a bunch of utility methods and properties. We can get information about the protocol, host, port, domain, etc from the browser URLs using these properties and methods. 


var args = window.location.search
let data = new URLSearchParams(location.search).get('reqId');
console.log(data)

Few Javascript or JQuery Tricks for array and operators

 1) Empty an array

var arr = [10 , 20 , 30 ];
arr.length = 0; // arr will be equal to [].


2) Truncate an array using length

Like the previous example of emptying an array, we truncate it using the length property.

var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90];
arr.length = 4; // arr will be equal to [10, 20, 30, 40].

As a bonus, if you set the array length to a higher value, the length will be changed and new items will be added with undefined as a value. The array length is not a read only property.

arr.length = 10; // the new array length is 10
arr[arr.length - 1] ; // arr [10, 20, 30, 40, 50, 60, 70, 80, 90, undefined];


3)Use logical AND/ OR for conditions

var foo = 10;
foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();


4) Comma operator

var a = 10;
var b = ( a++, 99 );
console.log(a);  // a will be equal to 10
console.log(b);  // b is equal to 99


5) Swap variables

let v1 = 'value 1';
let v2 = 'value 2';

[v1,v2] = [v2, v1];
console.log(v1, v2);


Wednesday, May 5, 2021

Export HTML table to Excel file

<!-- https://github.com/linways/table-to-excel -->

<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel@v1.0.4/dist/tableToExcel.js"></script>


function exportReportToExcel(c) {

  let table = $("#feedbackExport2Excel"); // you can use document.getElementById('tableId') as well by providing id to the table tag

  let fileName = "Feedback";

  TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag

    name: `${fileName}.xlsx`, // fileName you could use any name

    sheet: {

      name: 'Sheet 1' // sheetName

    }

  });

}//exportReportToExcel


Tuesday, February 2, 2021

Add days to a Date using JavaScript

Many times I have face this issue, and hope you too.. this is simple 3 line of code will help and fix this problem.


let days =7 ; // we are going to add 7 days to a date

let cdt = new Date('2021-01-10'); // your date value

let tdt = cdt.setTime(cdt.getTime() + (days * 24 * 60 * 60 * 1000)); // calculation for adding 7 days and adding to time

let targetDT = new Date(tdt).format("yyyy-MM-dd"); // converting back from time to date 

// Output for targetDT will be "2021-01-17"


// With function...

function addDays(theDate, days) {
    return new Date(theDate.getTime() + days*24*60*60*1000);
}

var newDate = addDays(new Date(), 5);


Hope this will help you...

Thursday, January 28, 2021

JavaScript to get index from a JSON object with value

 In modern browsers you can use findIndex:

But this function is not supported by even not so old versions of a few browser as well as in IE (EDGE supports it). So below is a workaround using javascript: You can use either Array.forEach or Array.find or Array.filter

This method takes little more overhead as it loops through the whole object to search for the match. So, for lengthy JSON data, this method is not suggested(even though it gets the work done).