AngularJS: Display the last four characters of a string and substitute the rest with 'X'

I am attempting to change the characters with X and make it look something like this XXXXXT123

This is what I have tried:

var sno = 'TEST123';
alert(sno.slice(0,3).replaceWith('X'));

However, I encountered an error in the console

Uncaught TypeError: sno.slice(...).replaceWith is not a function(anonymous function)

Answer №1

Try this technique (originally suggested by @georg):

sno.replace(/.(?=.{4})/g, "X");

This method will accomplish the task:

sno.replace(/^.+(?=....)/, function (str) { return str.replace(/./g, "X"); });

The initial regular expression /^.+(?=....)/ identifies all characters except for the last four.

Those identified characters are then passed into the custom function. The output of that function determines what the recognized characters should be substituted with.

replace(/./g, "X") swaps out every character with an X.

Answer №2

 const key = "RANDOM789";
  id.slice(3); 
  id.slice(-2); 

alert(Array(chars * 2).join('Y') + test.slice(5));

Answer №3

To achieve the desired outcome, one could utilize the following algorithm:

let identifier = 'EXAMPLE12345';
String.prototype.customReplace = function(startIndex, endIndex, newText) {
   return this.substr(0, startIndex) + this.substr(startIndex, endIndex).replace(/./g, 'X') + this.substr(endIndex);
};
identifier = identifier.customReplace(0, identifier.length - 3, "x");
console.log('modified identifier:', identifier); 

Answer №4

Here's a different approach with detailed explanations:

let code = 'CODE123';
let characters = 4;
let beginning = Array(code.length - characters + 1).join('Y'); // Forming an array and combining it with Ys, the length is increased by 1 to include all characters
let ending = code.slice(-4); // Selecting only the last 4 characters
alert(beginning + ending);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with jQuery show/hide not functioning properly?

My website has a sub-menu section with a shopping cart icon. When a user hovers over the icon, it reveals a hidden cart section. The user can then move the mouse into the cart section to remove items. The problem I'm facing is that if a user displays ...

Customizing demonstration code for EventDrops with D3.js (by marmelab) - what are the best strategies?

After discovering the non-Node.js version of the EventDrops library for D3 on GitHub, I successfully implemented the example on my own server. You can find more details and the example code in this blog post here. However, I'm currently facing two is ...

To enhance user experience, consider incorporating a 'Next Page' feature after the completion of every four paragraphs,

Here is a code snippet that can be used to print 'n' number of paragraphs: <% while(rs.next()){ String para=rs.getString("poems"); %> <p> <%=para%> </p> <!-- n number of p tags are printe ...

Creating sequential numbers using jQuery

Recently, I worked on a script (credit to Chyno Deluxe) that generates a list of menu items based on what is written in the input box. However, I now have a new requirement which involves generating a sequence of numbers to be added continuously. Here is ...

Exploring the World of Angular JS Services

Following the recommended practices, I am working on encapsulating my global functions into reusable factory services. In the provided code snippet, my objective is to execute a function that takes the string value of "Qprogress" from my JSON data, perform ...

A guide to retrieving the timezone based on a specific address using the Google API

I need to utilize the Google API time zones, which requires geocoding the address to obtain the latitude and longitude for the time zone. How can I achieve this using a value from a textarea? Here are the 2 steps: Convert the textarea value into a geoc ...

Adjust the path of an element as it decreases in size

Sorry for the weird title, but that's likely why I can't find the solution on my own. I'm experimenting with CSS animations and I want the form element to decrease in height from 100px -> 0, but I want it to collapse from the top to the ...

Tips for concealing the sorting number in the grid header

I have implemented angularjs ui-grid for sorting 4 columns in my grid. However, I want to hide the sort numbers displayed in the grid. I have searched for a solution or configuration through API but did not find anything helpful. Thank you. https://i.sta ...

What is the best way to create a feature in Vue that filters options in real-time as we type into a

In my Vue application, I am trying to implement dynamic filtering for the options in a search box as the user types. Currently, the search box displays the entire list of options without any filtering happening even when the user is typing. <el-form-it ...

Transforming text colors dynamically using Vue.js

Here is an Angular code snippet: <div [style.color]="'#' + prod.id.substring(0,6)"> <small>{{ prod.id }}</small> </div> Now I want to create a similar code using vue.js. ...

Encountered an error while trying to download a PDF document in React

I'm currently working on adding a button to my website portfolio that allows users to download my CV when clicked. The functionality works perfectly fine on my localhost, but after deploying it to AWS Amplify, I encountered an error. The error occurs ...

Is there a problem with AngularJS $state.go() not emitting $stateChangeSuccess?

In my scenario, I have controllers A and B located in different states. When I trigger $state.go('state_b');, Angular switches to state state_b and loads controller B. However, what surprises me is that I do not receive $stateChangeSuccess in my ...

Continuously converting methods recursively until the array is fully processed

My current code has a method that is not very efficient and does not scale well. The object y is an array consisting of key/value pairs, each containing two properties: 1. A unique string property called name. This value is identified by the childre ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

Using jQuery to target the element before

Is there a way to determine the width of elements located before an element when it is hovered over? I attempted to achieve this using the following code: $('ul li').hover(function() { $(this).prevAll().each(function() { var margin = $(this ...

React Router - Changing the URL path without affecting the components displayed

Facing an issue with React Router where the main page renders but other pages do not. I am using a library called react-responsive-animate-navbar for the Navigation bar, which works well and changes the URL when clicked. However, the specified component fo ...

Transferring information within React components

Looking for some assistance with the code below. I'm facing an issue where the data is not being submitted along with the form, even though the correct values are displayed in the form. I have included a user query to fetch data from another object an ...

Material User Interface, MUI, Modal, Back to Top Scroll按钮

After spending some time experimenting with scrollTop and the Dialog component (a fullscreen fixed modal) from Material-ui, I found that I couldn't quite get scrollTop to function properly. Whenever I clicked the "go down" button, it would either retu ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...