I am trying to write a Regular Expression that replaces all the digits of a number with *'s after first 4 digits.
For example
var number = 123456789
it should be replaced with 1234*****
I am trying to write a Regular Expression that replaces all the digits of a number with *'s after first 4 digits.
For example
var number = 123456789
it should be replaced with 1234*****
4 Answers
Reset to default 5In Javascript:
var maskedNumber = String(number).substr(0,4) + Array(String(number).length - 3).join('*');
In PHP:
$maskedNumber = str_pad(substr($number, 0, 4), strlen($number), "*");
In PHP:
function replaceDigit_callback($matches) {
return $matches[1] . str_repeat('*', strlen($matches[2]));
}
$text = '1234567890';
echo $text, "\n";
$text = preg_replace_callback('#(\d{4})(\d+)#', 'replaceDigit_callback', $text);
echo $text, "\n";
Output:
1234567890
1234******
In JS:
var number = 1234567890;
var output = number.toString().replace(/(\d{4})(\d*)/, function (str, p1, p2) { return p1 + p2.replace(/./g, '*') });
You Can set your PHP coding..I provide you logic....
using System;
using System.Text.RegularExpressions;
class RegexSubstitution
{
public static void Main()
{
string testString1 = "1, 2, 3, 4, 5, 6, 7, 8";
Regex testRegex1 = new Regex( @"\d" );
Console.WriteLine( "Original string: " + testString1 );
Console.WriteLine( "Replace first 3 digits by \"digit\": " + testRegex1.Replace( testString1, "digit", 3 ) );
}
}
Without regex:
var number = '123456789';
var output = '';
output = number.substr(0,4);
for ( var i = 0; i < number.length - 4; ++i )
{
output += '*';
}
Input number
has to be string !
Conversion
var number = 1234567890;
to string looks just like:
var number = 1234567890 + '';
or
var number = parseString(1234567890);