Javascript - Regex to replace last 4 digit - javascript

I have a number variable at JavaScript and i want it replaced in last 4 character. Example:
I have a number 123456789 and i want it to be replaced like this 12345****
Is there any regex to do that in JavaScript?

Use replace() with regex /\d{4}$/
var res = '123456789'.replace(/\d{4}$/, '****');
document.write(res);
Regex explanation
Or using substring() or substr()
var str = '123456789',
res = str.substr(0, str.length - 4) + '****';
document.write(res);

You could use substring as well:
var s = '123456789';
var ns = s.substring(0, s.length - 4) + '****';
document.write(ns);

Related

split a string from end till second space

I have a string i want to split it so that I can extract the name from the particular string.
let str = "CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
let splitstr= str.substr(3, str.indexOf(' -'))
console.log(splitstr)
Sample str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
I am doing this way but it displays the " - " too. How can i fix it?
You can split twice, first on the '=' and taking the second index then on the '-' and taking the first index. Add a trim() and you're good to go
const getName = str => str.split('=')[1].split('-')[0].trim();
let str = "CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
console.log(getName(str))
str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
console.log(getName(str2))
If you switch out substr() for slice() it works fine using the same start/end indices
const getName = str => str.slice(3, str.indexOf(' -'));
const str ='CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com',
str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
[str,str2].forEach(s=> console.log(getName(s)))

JavaScript: Add space between Char and Number with Regex

Hello I have a plate number BZ8345LK and want convert to BZ 8345 LK (adding space between char and number).
I tried with this Regex but not working, only space first char with number. Ex BZ 8345LK, the 'LK' keep not space with number.
var str = 'BZ8345LK';
str.replace(/[^0-9](?=[0-9])/g, '$& ');
# return BZ 8345LK, I want BZ 8345 LK
You can use this regex
[a-z](?=\d)|\d(?=[a-z])
[a-z](?=\d) - Match any alphabet followed by digit
| - Alternation same as logical OR
\d(?=[a-z]) - Any digit followed by alphabet
let str = 'BZ8345LK'
let op = str.replace(/[a-z](?=\d)|\d(?=[a-z])/gi, '$& ')
console.log(op)
You should alternate with the other possibility, that a number is followed by a non-number:
var str = 'BZ8345LK';
console.log(str.replace(/[^0-9](?=[0-9])|[0-9](?=[^0-9])/g, '$& '));
An anoher option is to use:
^[^\d]+|[\d]{4}
Search for any not numeric character [^\d] followed by 4 numeric [\d]{4} characters
const str = 'BZ8345LK'
let answer = str.replace(/^[^\d]+|[\d]{4}/gi, '$& ')
console.log(answer)
Try with this
var str = "BZ8345LK";
var result = str.replace(/([A-Z]+)(\d+)([A-Z]+)/, "$1 $2 $3");
console.log(result);

how to count digits of a phonenumber(included 0) in javascript?

I am trying to write a javascript , And want to count digits of a var str,
in the code below var str is 6 digits (012345), but when i run this code it is showing answer 4. i tried to search on google but answer not found;
how to get correct answer and fix it ?
my code
var str = 012345;
var x = String(str);
var n = x.length;
document.getElementById("demo").innerHTML = "var str is[" + n + "] Digits";
Initialize you phone number as string using quotes.
var str = '0123213'
And use length property to get its length
If you were to actually have a mixed letter/number string from which you wanted to get the number of digits you could use a regex. match creates an array of all the matches in the string - in this case \d, a digit (g says to check the whole of the string, not give up the search when the first digit has been found.) You can then check the length of the returned array.
'01xx2s3eg345'.match(/\d/g).length; // 7
try replacing the code with:
var str = "012345";
var n = str.length;
document.getElementById("demo").innerHTML = "var str is[" + n + "] Digits";

Regular Expression to add dashes to a phone number in JavaScript

function convertToValidPhoneNumber(text) {
var result = [];
text = text.replace(/^\d{2}-?\d{3}-?\d{3}-?\d{3}$/, "");
while (text.length >= 6){
result.push(text.substring(0, 3));
text = text.substring(3);
}
if (text.length > 0) result.push(text);
return result.join("-");
}
I test this function against 35200123456785 input string.
It gives me like a number like 352-001-234-56785 but I want 35200-12345678-5.
What do I need to do to fix this?
You can use this updated function that uses ^(?=[0-9]{11})([0-9]{5})([0-9]{8})([0-9])$ regex:
^ - String start
(?=[0-9]{11}) - Ensures there are 11 digits in the phone number
([0-9]{5}) - First group capturing 5 digits
([0-9]{8}) - Second group capturing 8 digits
([0-9]) - Third group capturing 1 digit
$ - String end
Replacement string - "$1-$2-$3" - uses back-references to those capturing groups in the regex by numbers and adds hyphens where you need them to be.
In case you have hyphens inside the input string, you should remove them before.
function convertToValidPhoneNumber(text) {
return text = text.replace(/-/g,"").replace(/^(?=[0-9]{11})([0-9]{5})([0-9]{8})([0-9])$/, "$1-$2-$3");
}
document.getElementById("res").innerHTML = convertToValidPhoneNumber("35200123456785") + " and " + convertToValidPhoneNumber("35-200-123-456-785");
<div id="res"/>
number = this.state.number;
var expression = /(\D+)/g;
var npa = "";
var nxx = "";
var last4 = "";
number = number.toString().replace(expression, "");
npa = number.substr(0, 3);
nxx = number.substr(3, 3);
last4 = number.substr(6, 4);
number = npa + "-" + nxx + "-" + last4

javascript - count spaces before first character of a string

What is the best way to count how many spaces before the fist character of a string?
str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
Use String.prototype.search
' foo'.search(/\S/); // 4, index of first non whitespace char
EDIT:
You can search for "Non whitespace characters, OR end of input" to avoid checking for -1.
' '.search(/\S|$/)
Using the following regex:
/^\s*/
in String.prototype.match() will result in an array with a single item, the length of which will tell you how many whitespace chars there were at the start of the string.
pttrn = /^\s*/;
str0 = 'nospaces';
len0 = str0.match(pttrn)[0].length;
str1 = ' onespace do not care about other spaces';
len1 = str1.match(pttrn)[0].length;
str2 = ' twospaces';
len2 = str2.match(pttrn)[0].length;
Remember that this will also match tab chars, each of which will count as one.
You could use trimLeft() as follows
myString.length - myString.trimLeft().length
Proof it works:
let myString = ' hello there '
let spacesAtStart = myString.length - myString.trimLeft().length
console.log(spacesAtStart)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/TrimLeft
str0 = 'nospaces';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
arr_str0 = str0.match(/^[\s]*/g);
count1 = arr_str0[0].length;
console.log(count1);
arr_str1 = str1.match(/^[\s]*/g);
count2 = arr_str1[0].length;
console.log(count2);
arr_str2 = str2.match(/^[\s]*/g);
count3 = arr_str2[0].length;
console.log(count3);
Here:
I have used regular expression to count the number of spaces before the fist character of a string.
^ : start of string.
\s : for space
[ : beginning of character group
] : end of character group
str.match(/^\s*/)[0].length
str is the string.

Categories