Mask function in javascript

Masking a string JavaScript

The above problem statement is about masking a substring within a string with the help of asterisks in Javascript. So we have to create a function to get the string with some hidden characters.

Understanding the problem statement

In the above problem statement we have to mask a substring within a string with the help of asterisks in Javascript. Masking a given string means we have to replace the certain characters in the given string with some other characters. Normally the asterisks used to hide sensitive information such as passwords, credit card numbers and other confidential data.

Logic for the above problem

The problem statement gives an example code snippet which shows how to implement a function which takes three parameters: the input string, the starting index of the substring to be masked and the ending index of the substring which is to be masked. The function will replace the characters in the substring with the asterisks and return the resulting masked string.

Читайте также:  Java override method final class

Algorithm

Step 1 − Create the function to get the masking string. This function will take input string str, the starting index and the ending index of substrings.

Step 2 − Check the condition for inputs if the string is invalid, empty, negative or greater than. If the condition is true then return the string as it is.

Step 3 − Calculate the mask length of the string. By getting the difference between ending point and starting point.

Step 4 − Then define the masked string by taking the start point and end point and place asterisks at the places where we have to hide the characters.

Step 5 − Return the masked string at the end of the function

Code for the algorithm

// function to get the masking the given string function maskingString(str, start, end) < if (!str || start < 0 || start >= str.length || end < 0 || end >str.length || start >= end) < return str; >const maskLength = end - start; const maskedStr = str.substring(0, start) + "*".repeat(maskLength) + str.substring(end); return maskedStr; > const inputStr = "9876543210"; const maskedStr = maskingString(inputStr, 2, 8); console.log(maskedStr);

Complexity

The problem statement mentions the complexity of the algorithm which is used to implement this function is O(n). Here n is the length of the input string. This means that the time the function takes to mask the substring is equally proportional to the length of the input string.

Conclusion

The above algorithm presents a common programming problem of masking a substring in a string and gives an example solution in Javascript with its complexity analysis.

Источник

imaskjsvanilla javascript input mask

IMask.Masked is a base class of all other Masked* classes. Almost all base class options are applicable to subclasses. Example usage:

const digitsMask = IMask(element,  mask: /^\d+$/ >);
mask.updateOptions( // while changing mask only same type allowed mask: /^\w+$/, // ok // mask: "0000", // ERROR! changing mask type on existing mask is not allowed! // . other options >);
masked.value = 'hello world!'; console.log(masked.unmaskedValue); // or typed value if it makes sense console.log(masked.typedValue);

Use prepare (value, masked) or prepareChar (value, masked) option for preprocessing input and commit (value, masked) option for postprocessing after UI is deactivated:

IMask(element,  mask: /^\w+$/, prepareChar: str => str.toUpperCase(), commit: (value, masked) =>  // Don't change value manually! All changes should be done in mask! // This example helps to understand what is really changes, only for demo masked._value = value.toLowerCase(); // Don't do it > >)

The difference between prepare and prepareChar is that when inserting multiple symbols in a batch prepare is called once for the entire string and prepareChar is called for each symbol. Usually you don’t need to create instances of that type manually, because it will be done by IMask internally. But you can subclass from Masked to add some specific behavior. Additionaly to mask option custom validator can be set as validate (value, masked) option for some complex checks on any mask types excluding Function and RegExp , because they are already validators themselves. Note: do not mutate Masked instance inside callbacks. Also make sure that mask or validator works with any of intermediate states, not just final value. For example to restrict input to «123» you do:

const masked = IMask.Masked( mask: /^123$/ >);

But it does not allow to input any symbol at all, because it matches only whole string «123» and not «1» nor «12». Always take care of intermediate values at first, otherwise it might not work as expected. In complex cases it is better to use Pattern or Function masks. Example of using Function mask to accept any growing sequence from 0 to 9:

IMask(element,  mask: value => /^\d*$/.test(value) && value.split('').every((ch, i) =>  const prevCh = value[i-1]; return !prevCh || prevCh  ch; >) >)

Источник

Mask function in javascript

WordPress 6 с Нуля до Гуру

WordPress 6 с Нуля до Гуру

Этот курс научит Вас созданию самых разных сайтов на самой популярной в мире CMS — WordPress. Вы увидите установку и настройку локального сервера, разбор каждой настройки, каждой кнопки и каждого пункта меню в панели WordPress.

Также Вы получите и всю практику, поскольку прямо в курсе с нуля создаётся полноценный Интернет-магазин, который затем публикуется в Интернете. И всё это прямо на Ваших глазах.

Помимо уроков к курсу идут упражнения для закрепления материала.

И, наконец, к курсу идёт ценнейший Бонус по тому, как используя ChatGPT и создавая контент для сайта, можно выйти на пассивный доход. Вы наглядно увидите, как зарегистрироваться в ChatGPT (в том числе, и если Вы из России), как правильно выбрать тему для сайта, как правильно генерировать статьи для него(чтобы они индексировались поисковыми системами) и как правильно монетизировать трафик на сайте.

Подпишитесь на мой канал на YouTube, где я регулярно публикую новые видео.

YouTube

Подписаться

Подписавшись по E-mail, Вы будете получать уведомления о новых статьях.

Подписка

Подписаться

Добавляйтесь ко мне в друзья ВКонтакте! Отзывы о сайте и обо мне оставляйте в моей группе.

Мой аккаунт

Мой аккаунт Моя группа

Источник

JavaScript input mask

The new input mask plugin brings a much better user experience. Now it considers the special keys, selections, and other user non-input actions on input elements with any JavaScript mask. In the newer version, it is possible to mask DIV.contentEditable HTML elements, and also it brings Excel-like mask options. The JavaScript mask integrates the user key down through events. Define the data-mask property in your input fields to start using.

  • React, Angular, Vue compatible;
  • Mobile friendly;
  • Date picker;
  • Time picker;
  • Year-month picker;
  • Several events and easy integration;
  • JS plugin or web component;

Examples

Using mask in HTML form elements

What is your birthday? (Mask: dd/mm/yyyy)

US Format (Mask: US #.##0,00)

How many liters (Mask: 0.00 liters)

EURO French Format (Mask: # ##0,00 €)

Using mask on contentEditable elements

Enter the currency price (Mask: U$ #.##0,00)

More examples

Advance masking combination

/** A few valid tokens can be used with mask as below: 0 0.00 0% 0.00% #,##0 #,##0.00 #,##0;(#,##0) #,##0;[Red](#,##0) #,##0.00;(#,##0.00) #,##0.00;[Red](#,##0.00) d-mmm-yy d-mmm dd/mm/yyyy mmm-yy h:mm AM/PM h:mm:ss AM/PM h:mm h:mm:ss m/d/yy h:mm mm:ss [h]:mm:ss */

More information about the jSuites JavaScript mask plugin

Источник

Input Text Masking Without a Plugin Using JavaScript

Input Text Masking Without a Plugin Using JavaScript

  1. Input Masking for Credit Card Numbers in JavaScript
  2. Zipcode Input Masking in JavaScript
  3. Telephone Number With Parenthesis Input Masking in JavaScript
  4. Customize the Input Masking for Different Fields in JavaScript

The JavaScript Input Mask or masked textbox is a control that provides an easy and reliable way for the user to collect input based on a standard mask. For example, it allows you to capture phone numbers, date values, credit card numbers, and other standard format values.

You may require enabling the users to enter only the specific data in a particular format in certain scenarios. For example, zip codes and credit card entries are within a specific pattern where you may restrict particular data formats.

The input-masking library allows the user to mask an input field using a particular data entry format.

This JavaScript module for masking input fields will make entries of spaces, dashes, and other characters automatically. As a result, users can concentrate solely on entering numbers or alphabets.

This is especially beneficial when data entry operators using a web interface are required to make many entries.

By going through the examples given below, you will learn how to set up this library on your web page.

Input Masking for Credit Card Numbers in JavaScript

In this example, a general format for the credit card is given. The user can try to enter numbers and alphabets without inputting the spaces.

You will see that the spaces are added automatically, as shown in the screenshot below.

Input Masking for Credit Card Numbers

You can access the code for this example below.

 html> head>   link rel="stylesheet" href="css/masking-input/masking-input.css"/>  style>  /* additional styles */  li line-height: 2; clear: both;>  label display: inline-block; width: 200px;>  .shell span color: pink;>  li font-family: helvetica; font-size: 0.93rem;>  style>  head>  body> ul> li>  label for="cc">Credit Card Numberlabel>  input id="cc" type="tel" name="ccnum" placeholder ="XXXX XXXX XXXX XXXX" pattern="\d \d \d \d" class="masked" title="Enter the 16 digits of credit card">  li>  ul>  script src="js/maskinginput/maskinginput.js" data-autoinit="true">script>  body>  html> 

Zipcode Input Masking in JavaScript

The zip code is a mix of alpha-numeric, so this is an interesting case for input masking. The placeholder for entering the zip code is made so that a user knows if a character is required or a number.

Zipcode Input Masking

Rather than using X in the placeholder, you saw that A1B2C3 was used, so you know the required format. You also do not need to enter the space; keep entering the code in the correct format.

The markup for creating the zip code input masked field is given below.

 html> head>   link rel="stylesheet" href="css/masking-input/masking-input.css"/>  style>  /* additional styles */  li line-height: 2; clear: both;>  label display: inline-block; width: 200px;>  .shell span color: pink;>  li font-family: helvetica; font-size: 0.93rem;>  style>  head>  body> ul> li>  label for="zipca">Enter zip codelabel>  input id="zipca" type="text" name="zipcode" placeholder="A1B2C3" pattern="\w\d\w\d\w\d" class="masked" datacharset="_X_ X_X" title="Enter zip code">  li>  ul>  script src="js/mask-input/mask-input.js" data-autoinit="true">script>  body>  html> 

Telephone Number With Parenthesis Input Masking in JavaScript

In this example, the telephone field will be masked, and the script will manage the parenthesis. This is shown in the screenshot below.

Telephone Number With Parenthesis

The code for this is given below.

 html> head>   link rel="stylesheet" href="css/masking-input/masking-input.css"/>  style>  /* additional styles */  li line-height: 2; clear: both;>  label display: inline-block; width: 200px;>  .shell span color: pink;>  li font-family: helvetica; font-size: 0.93rem;>  style>  head>  body> ul> li>  label for="tel">Enter Phonelabel>  input id="tel" type="tel" name="phone number" placeholder="(XXX) XXX-XXXX" pattern="\(\d\) \d\-\d" class="masked" title="Enter number without parenthesis">  li>  ul>  script src="js/mask-input/mask-input.js" data-autoinit="true">script>  body>  html> 

Customize the Input Masking for Different Fields in JavaScript

The most important thing to notice in all of the instances above is the pattern definition. For example, the following pattern is placed in the input field in the telephone example above.

If you want to allow the users to enter four digits in parenthesis rather than 3, change it to 4. To show how to customize the input fields, you will also add another dash, so this is how the pattern looks:

The user will also need to make changes in the placeholder as follows.

The screenshot for this is given below.

Customize the Input Masking for Different Fields

The code for this is given below.

 html> head>   link rel="stylesheet" href="css/masking-input/masking-input.css"/>  style>  /* additional styles */  li line-height: 2; clear: both;>  label display: inline-block; width: 200px;>  .shell span color: pink;>  li font-family: helvetica; font-size: 0.93rem;>  style>  head>  body> ul> li>  label for="tel">Enter Phonelabel>  input id="tel" type="tel" name="phone number" placeholder="(XXXX) XXX--XXXX" pattern="\(\d\) \d\--\d" class="masked" title="Enter number without parenthesis">  li>  ul>  script src="js/mask-input/mask-input.js" data-autoinit="true">script>  body>  html> 

Similarly, the user can also make the changes by adding the numbers or characters in the required format.

Related Article — JavaScript Input

Источник

Оцените статью