Selecting all characters in string between nth number and nth number Regex - javascript

I am trying to use regex in a jQuery function to select and mask all characters in a string with an'x' except the first 4 and last 4 characters. The string can be any length. I can successfully mask the last 4 digits and first 4 digits separately but I don't really understand regex well enough to select the nth character in a string to the nth character and mask them. If anybody can help it would be very grateful - I have spent many hours trawling around forums and trying to write my own regex but to no avail.
Thanks
My current function looks like this:
<input type="text" class="read-only-mask" title="" value="1233434343434456789012" name="" id=""readonly />
<script>
$(document).ready(function() {
$('.read-only-mask').val(function(_,val) {
return val.replace(/.(?=.{4})/g, 'x');
});
});
</script>
This would show 1233434343434456789012 as xxxxxxxxxxxxxxxxxx9012
I need it to show as 1233xxxxxxxxxxxxxx9012 but the string could be any length so 123343434343 would need to show as 1233****4343 etc

you are far better off using a simpler approach. Save your self some time and headache and use the KISS method.
var maxMaskLength = 10;
var minMaskLength = 4;
$(document).ready(function() {
$('.read-only-mask').val(function(_, val) {
var valSplit = val.split("");
for (i = minMaskLength; i < maxMaskLength; i++)
valSplit[i] = 'x';
return valSplit.join("");
});
});

I would prefer to do it like this
var str = "1233434343434456789012",
res = Array.prototype.map.call(str, (e,i) => i > 4 && i < 9 ? "X" : e).join("");
console.log(res);
var str = "1233434343434456789012",
res = Array.prototype.map.call(str, (e,i,a) => i < a.length-4 ? "X" : e).join("");
console.log(res);
whichever best fits your application.

I would use this way:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="read-only-mask" title="" value="1233434343434456789012" name="" id=""readonly />
<script>
$(document).ready(function() {
$('.read-only-mask').val(function(_, val) {
val = val.split("");
for (i = 4; i < val.length; i++)
val[i] = 'x';
return val.join("");
});
});
</script>
For the above input, it shows 1233xxxxxxxxxxxxxxxxxx. If that's what you need?

You really dont need regex for this, all you're doing is 3 substrings
string start to the mask start (1)
mask start to mask end (2)
mask end to string end. (3)
You then form the string back together by concatenating (1) above, the mask char to the length of (2) and finally (3).
var input = "1234567890";
var output = input.substring(0,4) + (Array(3).join('*')) + input.substring(6,10)
console.log(output)

You can use capturing parentheses:
"111122222333".replace( /(.{4})(.{5})(.*)/, '$1xxxxx$3');
1111 will be $1, replaced by itself.
22222 will be $2, replaced by xxxxx.
333 will be $3, replaced by itself.

Related

Insert line break every 3 lines in javascript?

Hi I'm still a newbie at javascript so I want to create a script that inserts a line break after every 3 lines. So here's my code I got so far
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.toString().match(/.{3}/g).join('</br>');
console.log(newNum);
It is doing it wrong. It seems to be inserting every 3characters instead of lines. Can anyone help me fix the code?
You can use the replace function. Try the below code.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/(.*\n.*\n.*\n)/g, '$1<br>');
console.log(newNum);
EDIT
I have made a few changes to the RegEx in the code below. This will allow you to specify the number of lines between which <br> need to be added.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/((.*\n){3})/g, '$1<br>');
console.log(newNum);
In the above RegEx, the .* will match all characters till the end of line and the \n will match the new line character.
(.*\n){3}
I have enclosed this in parenthesis to mark it as a group and used {3} to indicate that the preceding group repeats 3 times.
((.*\n){3})
Then the whole RegEx is enclosed in a parenthesis to use it as the first matched group that can be referenced in the replace section using $1.
You can replace the {3} with any number.
You should avoid using string manipulation when using HTML string. Also using BR to break line is not a good idea as well. You should use a block element instead.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var content = document.querySelector('.content');
var urls = num.split('\n');
var temp;
for(var i = 0; i< urls.length; i++) {
if(!temp || (i+1) % 3 === 0) {
if (temp) content.appendChild(temp);
temp = document.createElement('div');
}
var span = document.createElement('span');
span.classList.add('link')
span.innerHTML = urls[i];
temp.appendChild(span);
}
content.appendChild(temp);
.link {
margin: 5px;
}
<div class='content'>
Reference:
Is it sometimes bad to use <BR />?

how to replace a char in string with many chars

I want to change a char in string with many values
I have string like this :
date_format = "%m/%d/%Y";
And i want to replace ever % with the char which after, so the date variable should be like this:
date_format="mm/dd/YY";
Here is what I tried so far, but i can't get it to work, so I need some help here:
function replaceon(str, index, chr) {
if (index > str.length - 1) return str;
return str.substr(0, index) + chr + str.substr(index + 1);
}
function locations(substring, string) {
var a = [],
i = -1;
while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i);
return a;
}
function corrent_format(date_format) {
var my_locations = locations('%', date_format);
console.log(my_locations.length);
for (var i = 0; i < my_locations.length; i++) {
replaceon(date_format, my_locations[i], date_format[my_locations[i] + 1]);
}
return date_format;
}
console.log(corrent_format(date_format));
You can try this:
"%m/%d/%Y".replace(/%([^%])/g,"$1$1")
Hope this hepls.
You can use a regular expression for that:
var date_format="%m/%d/%Y";
var res = date_format.replace(/%(.)/g, "$1$1");
console.log(res);
function act(str) {
var res = "";
for (var i = 0; i < (str.length - 1); i++) {
if (str[i] === "%")
res += str[i + 1];
else
res += str[i];
}
res += str[i];
return res;
}
var date_format = "%m/%d/%Y";
console.log(act(date_format));
Your code is not working because the date_format variable is not being modified by the corrent_format function. The replaceon function returns a new string. If you assign the result to date_format, you should get the expected result:
for (var i = 0; i < my_locations.length; i++) {
date_format = replaceon(date_format, my_locations[i], date_format[my_locations[i]+1])
}
Alternatively, you could perform the replacement using String.replace and a regular expression:
date_format.replace(/%(.)/g, '$1$1');
For the regex-challenged among us, here's a translation of /%(.)/g, '$1$1':
/ means that the next part is going to be regex.
% find a %.
. any single character, so %. would match %m, %d, and/or %Y.
(.) putting it in parens means to capture the value to use later on.
/g get all the matches in the source string (instead of just the first one).
?1 references the value we captured before in (.).
?1?1 repeat the captured value twice.
So, replace every %. with whatever's in the ., times two.
Now, this regex expression is the most concise and quickest way to do the job at hand. But maybe you can't use regular expressions. Maybe you have a dyslexic boss who has outlawed their use. (Dyslexia and regex are uneasy companions at best.) Maybe you haven't put in the 47 hours screaming at regular expressions that aren't doing what you want, that you're required to put in before you're allowed to use them. Or maybe you just hate regular expressions.
If any of these apply, you can also do this:
var x = '%m/%d/%y';
x = x.replace('%', 'm');
x = x.replace('%', 'd');
x = x.replace('%', 'y');
alert(x);
This takes advantage of the fact that the replace function only replaces the first match found.
But seriously, don't use this. Use regex. It's always better to invest that 20 hours working out a regex expression that condenses the 20 lines of code you wrote in 15 minutes down to one. Unless you have to get it done sometime tonight, and whatever you're trying just doesn't work, and it's getting close to midnight, and you're getting tired...well, no. Use regex. Really. Resist the temptation to avoid finding a regex solution. You'll be glad you did when you wake up at your desk in the morning, having missed your deadline, and get to go home and spend more time with your family, courtesy of your generous severance package.

Select string before some letters

If I have
var x = "3558&Hello world!&538345";
Now for selecting after I can use:
var y = x.split("&");
But I want to know can I select it before some char?
I need to get var z = 3558...
I don't want to select letters and nums from 0 to 4 because I don't know what is the length of numbers.... So is there any way to say select all before & ?
You're using the split functionality, so just grab the value at position 0 of the resulting array, that will be the substring up until the first &.
var y = x.split ("&")[0];
try this:
var y = x.split('&')[0]; // y = "3558"
You can use String.prototype.replace() with RegExp /&.+/ to match "&" and characters that follow, replace match with empty string
var z = "3558&Hello world!&538345".replace(/&.+/, "")
Lots of options! :D
function bySplit (textStr, delimiterStr) {
return textStr.split(delimiterStr)[0]
}
function byRegexReplace (textStr, delimiterStr) {
return textStr.replace(new RegExp(delimiterStr+'.*'), '')
}
function byRegexExec (textStr, delimiterStr) {
return (new RegExp('^(.*)'+delimiterStr)).exec(textStr)[1]
}
You could also write for or while loop to add chars to a result unless they encounter a matching delimiterStr, but they get messy compared to these three.

get only number from value and calculate the length from text field

I HAVE A TEXT FIELD
<input id="prime-phone" class="number-format" name="prime-phone" placeholder="" type="tel">
and there if fix value and it would be "(432)432-2432".
I want to count the length of number only not the special character like "(" , "-"
I am trying in this way and i also know i am doing somthing wrong
sd = $(".number-format").val();
alert(sd);
sd = parseInt(sd)
alert(sd)
number format can be change like "(432)432-2432" , "(43)-(432)-2432"
Thanks
in advance for the help :)
var sd = $(".number-format").val();
//i want to count the length of number only not the special character like "(" , "-"
var len = sd.match(/\d/g).length;
try it
Use regex to match the digits and count:
sd.match(/\d/g).length
Remove non digit character using replace() and count
sd=$(".number-format").val();
alert(sd);
len=sd.replace(/\D/g,'').length;
// \D used to match all non-digit character
alert(len);
DEMO
A reusable solution.
once defined you could just call them to exclude the unwanted characters and get the length.i find this easier to maintain.
var tel = "(432)432-2432";
var getLength = function(tel){
var telStr = tel.split('');
var excpetionList = ['(',')','-']; //<-- here you can add the chars to remove
return telStr.filter(function(item,index,arr){
if(excpetionList.indexOf(item) < 0){
return item;
}
}).join('').length;
};
console.log(getLength(tel));
demo

Jquery check if special char exists in text value

i need to check if a textarea contains some special characters, so i need to count them 2 (SMS lenght).
I wrote this piece of code but seems that it doesn't find no special chars, also if write only "€€€"
Could you please help me? Also if you would to rewrite directly function, without problem. Thank tou!
var SPECIAL_CHARS = Array('€', '%');
function charUsed() {
var count = $('#text').val().length;
var chars = $('#text').val().split("");
var numberOfSpecialChars = 0;
if ($.inArray(chars, SPECIAL_CHARS) > -1) {
numberOfSpecialChars++;
}
return count + numberOfSpecialChars;
} // function
A rewrite :
var nbSpecialChars = $('#text').val().split(/[€%]/).length - 1;
The idea is to make an array of strings, using your special characters as separator :
'some € chars %' => ["some ", " chars ", ""]
and then use the length of this array to deduce the count of those chars. There are many other (faster) solutions but this one is short.
http://jsfiddle.net/KSm7J/
var chars = $('#text').val().match(/[€%]/g).length;
alert(chars);

Categories

Resources