I have some code that matches a certain number of digits after a decimal. Currently, I have the following:
var input = getValueFromUser();
var count = getCount();
var x = Number(input.toString().match(/^\d+(?:\.\d{0,1})?/));
alert(x);
This approach always gets the first digit after the decimal. However, I want to replace the 1 in the regex with the value in count. How do I do that? I tried the following:
var pattern = '/^\d+(?:\.\d{0,' + count + '})?/';
var x = Number(input.toString().match(pattern));
However, now, I always get 0 for x.
You have to use Regexp object if you want to use dynamically built patterns:
var re = new RegExp('^\\d+(?:\\.\\d{0,' + count + '})?');
This will help you.
var pattern = '^\\d+(?:\\.\\d{0,' + '5' + '})?',
reg=new RegExp(pattern),
x = Number(input.toString().match(reg));
mask: new RegExp(`^[a-zA-Z0-9]{0,${maxLength}}$`)
its work for me
var alien = 'ajay'+' $%';
var all=new RegExp(`${alien}`)
Related
12:00:00:12
How to remove 6 character from the back? the output would be 12:00, I can't use substring to get the from the front to get the 6 char, because it can be 9:00 so it's just 4 char instead of 5.
I think #ZakariaAcharki is a better solution but if you want make it by substring try this:
str = '12:00:00:12';
str.substring(0,str.length-6);
I think better if you use split() function, and take the first and second items in splited array.
var my_string ="12:00:00:12";
var array_splited = my_string.split(':');
console.log( array_splited[0] + ':' + array_splited[1] ); //12:00
If you want it in single line, e.g :
my_string.split(':')[0] + ':' + my_string.split(':')[1];
Hope this helps.
You can determine the length and than go back 6 chars e.g.
str = '12:00:00:12'
str = str.substring(0,str.length - 6);
But you may better match with
str = '12:00:00:12'.match(/^[0-9]+:[0-9]+/)[0]
A regular expression with .match() method will do:
var str1 = '12:00:00:12';
var str2 = '9:40:00:12';
var regex = /(\d+)+:+(\d\d)/g;
var newStr1 = str1.match(regex)[0];
var newStr2 = str2.match(regex)[0];
document.querySelector('#one').textContent = JSON.stringify(newStr1);
document.querySelector('#two').textContent = JSON.stringify(newStr2);
'12:00:00:12' <pre id='one'></pre>
<hr>
'9:40:00:12' <pre id='two'></pre>
var str = "12:00:00:12";
var newStrArr = str.split(":");
newStrArr.pop();
newStrArr.pop();
newStrArr.join(":");
If the time will always be in the form (0-12):(00-59);(00-59) then you could use regex and the function .match() to get the time in the format you would like:
current_time = '12:00:00'
time_formatted = current_time.match(/\d+:\d+/)
Try using split and join.
EG 1:
var num = "12:00:00:12";
console.log(num.split(':', 2).join(':'));
EG 2:
var num = "9:00:00:12";
console.log(num.split(':', 2).join(':'));
Simple and best solution:
Use slice() function.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(function(){
var str = '12:00:00:12';
alert(str.slice(0,-6));
});
Output: 12:00
JSFiddle Demo
I have the following string: 0-3-terms and I need to increment the 3 by 20 every time I click a button, also the start value might not always be 3 but I'll use it in this example..
I managed to do this using substring but it was so messy, I'd rather see if it's possible using Regex but I'm not good with Regex. So far I got here, I thought I would use the two hyphens to find the number I need to increment.
var str = '0-3-terms';
var patt = /0-[0-9]+-/;
var match = str.match(patt)[0];
//output ["0-3-"]
How can I increment the number 3 by 20 and insert it back in to the str, so I get:
0-23-terms, 0-43-terms, 0-63-terms etc.
You're doing a replacement. So use .replace.
var str = '0-3-terms';
var patt = /-(\d+)-/;
var result = str.replace(patt,function(_,n) {return "-"+(+n+20)+"-";});
Another option is to use .split instead of regex, if you prefer. That would look like this:
var str = '0-3-terms';
var split = str.split('-');
split[1] = +split[1] + 20;
var result = split.join('-');
alert(result);
I don't understand why you are using regex. Simply store the value and create string when the button is called..
//first value
var value = 3;
var str = '0-3-terms';
//after clicking the button
value = value+20;
str = "0-" + value + "-terms"
I have a number let's say
305060
And I want to put a : at the -2 and -4 spot so I end up with
30:50:60
And if I entered 5006070 I would end up with 500:60:70
I can't seem to figure out how to do this.
Use this code:
var number = 123456789;
var formatted = number.toString().replace(/^(\d+)(\d{2})(\d{2})/, '$1:$2:$3');
alert(formatted);
Demo: http://jsfiddle.net/U4J6n/
If number is a string, you can remove the .toString() method from the code.
You could use a regex that catches the two last groups of two numbers
/(\d{2})(\d{2})$/
so it's
var x = 305060;
x = x.toString().replace(/(\d{2})(\d{2})$/, ":$1:$2"); // 30:50:60
var x2 = 5006070;
x2 = x2.toString().replace(/(\d{2})(\d{2})$/, ":$1:$2"); // 500:60:70
FIDDLE
Lets suppose n is the length of the string, first you want to take the number from 0 to n-4 then n-4 to n-2 and finally n-2 to n, so simply use one of substring or slice to get the solution.
If you want to use substring then it would be
var num="305060";
var length=num.length;
var ans=num.substring(0,length-4)+":"+num.substring(length-4,length-2)+":"+num.substring(length-2,length);
alert(ans);
If you want to use slice then
var num="305060";
var length=num.length;
var ans=num.slice(0,length-4)+":"+num.slice(length-4,length-2)+":"+num.slice(length-2,length);
alert(ans);
substr is another function in javascript which will help you to get the solution
var num="305060";
var length=num.length;
var ans=num.substr(0,length-4)+":"+num.substr(length-4,2)+":"+num.substr(length-2,2);
alert(ans);
You can use String.prototype.slice
Javascript
var x = 305060,
y = x.toString(),
z = [y.slice(0, -4), y.slice(-4, -2), y.slice(-2)].join(':');
console.log(z);
Output
30:50:60
On jsFiddle
I asked a similar question yesterday .. If I have for example 0-9999 , how can I turn this into 09999 , basically removing the - and make it an integer in javascript ?
var = 0-9999
turn that into 9999 integer
or var = 2-9999 , turn that into 29999
Thanks a bunch
This should do the trick:
num = num.replace(/[^0-9]+/g, '') * 1;
It'll strip out any non-numeric characters and convert the variable into an integer. Here's a jsFiddle demonstration for you.
The most obvious and basic of solutions would be:
var s = "1-2345";
var t = s.replace("-","");
var i = parseInt(t,10);
But that's making a lot of assumptions and ignoring any errors.
Try this:
var i = '0-9999';
var int = Number(i.replace('-', ''));
window.alert(int);
Note in Firefox, parseInt() won't work with leading zeros unless you pass in a radix (this appears to be a bug):
var int = parseInt(i.replace('-', ''), 10);
Fiddler
Remember that
var x = 2-9999
is the same as
var x = -9997
because the dash is seen as a subtraction symbol unless you use quotation marks (Single or double, doesn't matter).
So, assuming that you properly quote the text, you can use the following function to always pull out a character that is in any given spot of the text (Using a zero-based index).
function extractChar(myString,locationOfChar){
var y = myString.substring(0,locationOfChar-1)
var z = myString.substring(locationOfChar+1)
var s = y.concat(z)
var i = parseInt(s,10)
return i
}
therefore
var i = extractChar("2-9999",1)
Will be the same as
var i = 29999
I want to extract the date and the username from string using .split() in this particular string:
var str ='XxSPMxX on 08/30/2012';
I want XxSPMxX in one variable and 08/30/2012 in the other.
Using just split:
var x = str.split('</a> on ');
var name = x[0].split('>')[1];
var date = x[1];
Demo: http://jsfiddle.net/Guffa/YUaAT/
I don't think split is the right tool for this job. Try this regex:
var str ='XxSPMxX on 08/30/2012',
name = str.match(/[^><]+(?=<)/)[0],
date = str.match(/\d{2}\/\d{2}\/\d{4}/)[0];
Here's the fiddle: http://jsfiddle.net/5ve7Y/
Another way would be to match using a regular expression, build up a small array to get the parts of the anchor, and then use substring to grab the date.
var str = 'XxSPMxX on 08/30/2012';
var matches = [];
str.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function () {
matches.push(Array.prototype.slice.call(arguments, 1, 4))
});
var anchorText = matches[0][2];
var theDate = str.substring(str.length - 10, str.length);
console.log(anchorText, theDate);
working example here: http://jsfiddle.net/dkA6D/