Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have some date as below.
I want to mask these values.
const name = "Smith"
const name2 = "Kithmatch"
const number = "342782828"
const number2 = "012221112230"
After masking,
const name = "S***h"
const name2 = "K*******h"
const number = "342**2828"
const number2 = "012*****2230"
There are two conditions between name and number.
In name only first and last string survive. And in number three number from front and four number from end survive.
How can I make this masking in javascript? Thank you so much for reading it.
You simply take the start and the end and insert the * with the repeat function. The start and end variables can simply be adjusted. String slice gets a part of a string which we will take to insert with +=
Note that if there are too less characters, no * will be inserted.
var s = "342782828";
var start = 1;
var end = 1;
if (!isNaN(s)) { // check if is number
start = 3;
end = 4;
}
result = s.slice(0, start);
result += "*".repeat(s.length-start-end);
result += s.slice(s.length-end);
console.log(result);
I don't know if this can be achieved with regex.
For a JS solution you can look at the snippet below.
It uses the substring, slice and repeat methods of String.
The substring() method returns the part of the string between the start and end indexes, or to the end of the string.
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
Learn more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Methods
const name = "Smith"
const name2 = "Kithmatch"
const number = "342782828"
const number2 = "012221112230"
const maskName = (name) => {
const mask = "*";
let maskedName = name.substring(0,1) + mask.repeat(name.length-2) + name.slice(-1);
return maskedName;
};
const maskNumber = (number) => {
const mask = "*";
let maskedNumber = number.substring(0, 3) + mask.repeat(number.length-7) + number.slice(-4);
return maskedNumber;
};
console.log(maskName(name));
console.log(maskName(name2));
console.log(maskNumber(number));
console.log(maskNumber(number2));
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a Array of Strings. Its a text with enumeration. So its like "1. abcde. 2. fghijk.
There is no new line. I want to write a loop that detects the place where the "2." is and the place before it (array[I-1]) there should be included a \n for the new line. But I don't know a command for place a new element in an array without deleting the existing element on the same place.
How can I do that ?
This is the code I got till now:
let el = document.getElementById('textinhalt').textContent;
for(let i = 0; i<el.length; i++){
if(el[i]=="2" && el[i+1]=="."){
}
}
You don't need loop. You can simply use replace or replaceAll
both takes regex as needle, so you can check for another digits like 2., 3., 4., 5. and so on with /([2-9]\.)/ - this regex will find all signle digits with . after it, that is not 0 or 1
try this regex at regex101 and see how it works
let el = document.getElementById('textinhalt').textContent;
document.getElementById('textinhalt').innerHTML = el.replace(/([2-9]\.)/, '<br>$1');
<div id="textinhalt">1. abcde. 2. fghijk</div>
UPDATE
for bigger number I would suggest another regex
/(?:[^1](\d+\.))/g and you can test it again on regex101
demo:
let el = document.getElementById('textinhalt').textContent;
document.getElementById('textinhalt').innerHTML = el.replaceAll(/(?:[^1](\d+\.))/g, '<br>$1');
<div id="textinhalt">1. abcde. 2. fghijk 15. asdasd 10000. dsfsdfsdfsd</div>
You would have to parse the text, insert the line before the index, and serialize it.
const parse = (text) => text.split(/\s*\d+\.\s/).filter(l => l.length > 0);
const serialize = (arr) => arr.map((l, i) => `${i + 1}. ${l}`).join(' ');
const insertBefore = (arr, i, val) => arr.splice(i, 0, val);
const text = '1. abcde. 2. fghijk.';
const arr = parse(text);
insertBefore(arr, 1, 'Hello World.');
arr.push("I'm last!");
console.log(serialize(arr));
I have used the below code to split my string.
splitter.map((item1) => {
let splitter1 = item1.split("=")[0].trimLeft();
let splitter2 = item1.split("=")[1].trimRight();
});
where item1 contains string as
Labor_Agreement=0349BP
Default_Hours=5/8
Probation_Period=>=12 Months
The issue I am facing is to restrict the amount of splits. Because the above code will fail in case of third string , i.e. Probation_Period=>=12 Months
I tried giving parameter to restrict the amount of split in split method above, but that is giving syntax error.
An easy to understand solution would consist of first finding the first = character, and slicing you array twice to get the right portion :
const strings = [
'Labor_Agreement=0349BP',
'Default_Hours=5/8',
'Probation_Period=>=12 Months',
];
strings.map(item => {
const chSplit = item.indexOf('=');
const splitter1 = item.slice(0, chSplit).trim();
const splitter2 = item.slice(chSplit + 1).trim();
console.log(splitter1, splitter2);
});
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I work with JavaScript on my bachelor thesis.
I would like to read a string and mark the elements that are the same and follow each other in the same color.
I have not found a good approach yet.
I would be grateful for a good proposal.
This is what i have right now.
function colorsetting(input){
var collength = input.length;
var now = '', last2 = '', colored = '';
now = last2 = input[0];
for(var i = 1; i <= collength, i++){
if(now !== last2){
colored = last2.fontcolor("green");
last2 = now;
}
now = input[i];
}
colored = last2.fontcolor("red");
return colored;
}
You can split up your input string using a regex:
/(.)\1*/g
(.) grabs any character, and stores that in capture group 1.
\1* then tells the regex to match as many of those as it can.
Then, iterate over that array, wrap the strings in a span, each with their own colour.
const str = "aaaabbbb123aaaaccccz";
const result = str.match(/(.)\1*/g);
console.log(result);
result.forEach(t => {
// Create a span element
const span = document.createElement("span");
// Set the text in that span to be the current match
span.innerText = t;
// Set the span's color to something random.
span.style.color = "#"+((1<<24)*Math.random()|0).toString(16);
document.body.append(span);
})
(random color code from here)
I'm trying to mask a portion of a string using JavaScript.
e.g. Mask second and third segment of credit-card number like this using regex:
4567 6365 7987 3783 → 4567 **** **** 3783
3457 732837 82372 → 3457 ****** 82372
I just want to keep the first 4 numbers and the last 5 characters.
This is my first attempt: /(?!^.*)[^a-zA-Z\s](?=.{5})/g
https://regex101.com/r/ZBi54c/2
You can try this:
var cardnumber = '4567 6365 7987 3783';
var first4 = cardnumber.substring(0, 4);
var last5 = cardnumber.substring(cardnumber.length - 5);
mask = cardnumber.substring(4, cardnumber.length - 5).replace(/\d/g,"*");
console.log(first4 + mask + last5);
You could slice the first four digits and apply a replacement for the rest.
console.log(
['4567 6365 7987 3783', '3457 732837 82372'].map(
s => s.slice(0, 4) + s.slice(4).replace(/\d(?=.* )/g, '*')
)
);
The answer apparently satisfies the OP. Here is another solution using only Regexes:
function starry(match, gr1, gr2, gr3) {
var stars = gr2.replace(/\d/g, '*');
return gr1 + " " + stars + " " + gr3;
}
function ccStarry(str) {
var rex = /(\d{4})\s(\d{4}\s\d{4}|\d{6})\s(\d{4}|\d{5})/;
if (rex.test(str))
return str.replace(rex, starry);
else return "";
}
var s1 = "4567 6365 7987 3783";
var s2 = "3457 732837 82372";
var s3 = "dfdfdf";
console.log(ccStarry(s1));
console.log(ccStarry(s2));
console.log(ccStarry(s3));
This ensures that the pattern matches before trying any replacements. For example, in the third test case, it returns an empty string. The pattern can be updated to match other credit card patterns besides the ones given in the question.
I would like to elaborate more on the answer from #Nina Scholz, I use .slice() in the following sample code for masking the variable in 2 condition.
Just a simple variable var n = '12345567890'
Array object
// Single number
var n = '601115558888';
var singleNumber = n.slice(0, 4) + n.slice(4, n.length -4).replace(/\d/g,'*') + n.slice(n.length -4);
console.log(singleNumber);
// array of object
var obj = [{
contacts_name: 'Jason',
contacts_num : '651231239991'
},
{
contacts_name: 'King',
contacts_num : '60101233321'
}];
// Mask for the middle number, showing the first4 number and last4 number
// and replace the rest number with *
var num = obj.map((element, index) =>
element.contacts_num.slice(0,4)
+ element.contacts_num.slice(4, element.contacts_num.length-4).replace(/\d/g, '*')
+ element.contacts_num.slice(element.contacts_num.length -4)
);
console.log(num);
If it's JavaScript doing the regex masking, you've already failed because JS should never need to know the original card number, except when you've just received it from the user and are sending it to the server for the first time, in which case you shouldn't be masking it anyway so the user can check for typos.
I can't really help you there, you've already failed in the worst way.
Server-side, if the number is already broken into spaces*, then one option is: (in PHP but the same idea applies to all)
$parts = explode(" ",$fullnumber);
$first = array_shift($parts);
$last = array_pop($parts);
$middle = implode(" ",$parts);
$mask = preg_replace("/\d/","*",$middle);
$result = "$first $mask $last";
* it shouldn't be
This is a follow on from my previous question which can be found here
Link For Previous Question
I am posting a new question as the answer I got was correct, however my next question is how to take it a step further
Basically I have a string of data, within this data somewhere there will be the following;
Width = 70
Void = 40
The actual numbers there could be anything between 1-440.
From my previous question I found how to identify those two digits using regular expression and put them into separate fields, however, my issue now is that the string could contain for example
Part Number = 2353
Length = 3.3mm
Width = 70
Void = 35
Discount = 40%
My question is;
How do I identify only the Width + Void and put them into two separate fields, the answer in my previous question would not solve this issue as what would happen is in this example I would have an array of size 4 and I would simply select the 2nd and 3rd space.
This is not suitable for my issue as the length of array could vary from string to string therefore I need a way of identifying specifically
Width = ##
Void = ##
And from there be able to retrieve the digits individually to put into my separate fields
I am using JavaScript in CRM Dynamics
A simpler option is to convert the whole string into an object and get what you need from that object.
str = "Part Number = 2353\n" +
"Length = 3.3mm\n" +
"Width = 70\n" +
"Void = 35\n" +
"Discount = 40%\n";
data = {};
str.replace(/^(.+?)\s*=\s*(.+)$/gm, function(_, $1, $2) {
data[$1] = $2;
});
alert(data['Width']);
Width\s+=\s+(\d+)|Void\s+=\s+(\d+)
You can try this.Grab the capture.See demo.
http://regex101.com/r/oE6jJ1/31
var re = /Width\s+=\s+(\d+)|Void\s+=\s+(\d+)/igm;
var str = 'Part Number = 2353\n\nLength = 3.3mm\n\nWidth = 70\n\nVoid = 35\n\nDiscount = 40%';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
You can use this regex for matching input with Width and Void in any order:
/(\b(Width|Void) += *(\d+)\b)/
RegEx Demo
Your variable names and values are available in captured groups.