Insert space after certain character into javascript string - javascript

I'm working on a form and I'd like to mask the input of the phone numbers. The plugins what I found aren't okay for me since the area code could be 1 or 2 character long.
What I'd like to do is the following:
when the user types his number after the first two character the script inserts a space on keyup, then after the next three and later after every fourth character.
So when someone types 44444444444 then in the textbox appears 44 44 444 4444.
I must check the second group as well, and when someone types there for example 1, the the number must look like: 44 1 444 4444
Is any solution to do that?

You could do something like this:
http://jsfiddle.net/ffwAA/4/
Which applies this function to the string to get the desired formatting:
function formatCode(str){
var result = str;
str = str.replace(/\D+/g, "");
var m = str.match(/^(\d\d)(?:([2-90]\d|1)(?:(\d\d\d)(\d+)?)?)?$/);
if(m){
result = m[1] + " ";
if(m[2]) result += m[2] + " ";
if(m[3]) result += m[3] + " ";
if(m[4]){
result += m[4].split(/(\d{4})/).join(" ");
result = result.replace(/\s+/g, " ");
}
}
return result;
}
And using this jQuery to set it up:
function update(obj){
var val = obj.value;
var got = formatCode(val);
if(got != val)
obj.value = got;
}
var timer;
var prev_val = "";
$('#code').keyup(function(){
clearTimeout(timer);
// when adding numbers at the end of input, update at once
// don't want to update when editing in the middle of the string or removing parts of it
// because it would move the carret location to the end of input, and make it unusable
if(this.value.indexOf(prev_val) == 0){
update(this);
prev_val = this.value;
return;
}
prev_val = this.value;
// in other cases update 1 second after the changes are done
timer = setTimeout(update, 1000, this);
});

Have you tried the maskedInput plugin?
http://digitalbush.com/projects/masked-input-plugin/
I think it can solve your problem.
Hope this helps. Cheers

Related

Javascript Math.log() help wanted

World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.

Mask a portion of a String using RegExp

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

Put line break after 10 characters in text area

I have a text area that can take 10000 characters. i want to put the line breaker on each line of the text area value after 10 character
something like this i want to achive
11111111 1
111 111 11
11 11 11 1
all above line has 10 characters each.
var start = 3
var times = 1;
$('.mydesc').keyup(function () {
var len = $(this).val().length;
if (len == start) {
this.value += '\n';
times = ++times;
start= ((start * 2) + start);
}
});
but doesn't work ..
Simplest solution is to always re-add all of the new-lines:
$('.mydesc').keyup(function () {
this.value = this.value
.replace(/[\n\r]+/g, "")
.replace(/(.{10})/g, "$1\n");
});
http://jsfiddle.net/s4cUz/
Something like this would do it:
http://jsfiddle.net/Zxuj7/
$('#test_textarea').keyup(function () {
var new_stuff = $(this).val();
new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
var test = new_stuff.replace(/(.{10})/g,"$1\n");
$(this).val(test);
});
However, be aware that it doesn't work that well with the "deleting" of characters. If you give it a go, you will notice that when you actually delete a character and the code runs, it will put you at the end of the textarea again (because its "overwriting" the value)
UPDATE:
You may actually be better formatting AFTER they have finished editing the textarea - i.e using blur();
$('#test_textarea').blur(function () {
// leaving the field... so lets try and format nicely now
var new_stuff = $(this).val();
new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
$(this).val(new_stuff);
});
Although that doesn't do it in real time - it does work better when deleting/editing the contents
Enhanced version of Andrew Newby's script:
$('#test_textarea').keyup(function (e) {
if (e.keyCode === 8) return; // Backspace
var new_stuff = $(this).val();
new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
$(this).val(new_stuff);
});
This actually ignores backspace key, so at least that interaction is preserved.

How can I redirect to another page if a field has been entered 12345?

There is a field <input> with the id "page", and I got it with document.getElementById('page'). I now try to read the value with getValue(), but nothing happens - what I am doing wrong?
The idea here is the:
Into the input field I entered 12345678910 and then determine that the first five digits are 12345 so the page 12345.html is opened. If I enter 1234581530 it will also open 12345.html. So you need only read the first five digits and then open the file you want, I hope understood my idea.
Sorry for the question, but I am still learning, I would be very grateful if you would give me some examples.
Thanks in advance!
There is no getValue method. You should read value property:
var page = document.getElementById('page').value.substr(0, 5);
location.href = page + '.html';
Demo: http://jsfiddle.net/q8bQc/
You can try something like this.
To get the value (there is no getValue, just value)
var str = document.getElementById('page').value;
To cut it to 5 chars -
str = str.substring(0, 5); // or substr(0, 5)
To open a different link -
location.href = str + '.html';
Or as a single line -
location.href = document.getElementById('page').value.substring(0, 5) + '.html';
You can use sub string to get the first 5 characters:
var str = value = document.getElementById('page').value; // The input
var res = str.substring(0,5); // The first 5 characters
And then some if statement to determine if they equal 12345
if(res == "12345") {
};
Now all you need to do is open the link which can be done like:
window.open("/12345.html","_self")
Which will open the link in the same window
All together:
var str = value = document.getElementById('page').value; // The input
var res = str.substring(0,5); // The first 5 characters
if(res == "12345") {
window.open("/12345.html","_self")
};
First set the element value then cut it and open the link
var value = document.getElementById('page').value;
value = value.substring(0, 5);
window.open(value + '.html') //To Open in a new tab
window.open(value + '.html','_self') //To Open in the same tab
http://jsfiddle.net/52vtQ/
$(function () {
var a;
$("#sub").click(function () {
a = $('#page').val();
alert(a);
});
});
maybe this will help you out with your problem

Count carriage returns in javascript

I'm running the following code to set a limit on characters in a textarea:
(function($){
$.fn.extend({
limit: function(limit,element) {
var interval, f;
var self = $(this);
$(this).focus(function(){
interval = window.setInterval(substring,100);
});
$(this).blur(function(){
clearInterval(interval);
substring();
});
substringFunction = "function substring(){ var val = $(self).val();var length = val.length + carriages;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
if(typeof element != 'undefined')
substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
substringFunction += "}";
eval(substringFunction);
substring();
}
});
})(jQuery);
The area my users are entering text into can fit a maximum of 1500 characters. The problem is that it can only fit a maximum of 10 lines. If they enter 25 characters on one line before entering a carriage return, the characters total needs to be at 150, not 26.
How can I accomplish this?
var string = "foo\nbar\nbaz";
console.log(string);
// foo
// bar
// baz
var lines = string.split(/\n/).length;
Simply split the string by every new lines, and then see how many lines you have.
Another solution using regex that is always very efficient. Note that this solution counts retuen carriages, NOT lines
const string = "foo\nbar\nbaz";
const lines = (string.match(/\n/g) || []).length;
console.log(lines);

Categories