var result="stackoverflow";
var string="22342st";
if(more than 3 letters)
{
var new=data;
}
1)how I can get variable if only have more than
using match() (function ) in javascript
2)what if I do getting variable in for time delay
some (because of TCP connection)
Does anyone have an idea?
you can use .length property to check string length is greater than 3 or not.
var result = "stackoverflow";
if(result.length > 3)
{
//Your business logic goes here
}
if you want to check only character counts in string is greater than three then you can try below code
var input = "45749ce";
var result = input.match(/[a-zA-Z]/gi);
if(result.length > 3)
{
//Your business logic goes here
console.log(`${result} length is greater than 3`);
}
That should work
var myRegEx = /[a-zA-Z(.+)]{3}/g;
var myString="22342st";
if(myString.match(myRegEx)!==null)
{
}
Also
myString.match(myRegEx)
will return an array of matched values, so you can work with them if needed.
To find the more than three letter in variable using match you have to need regex
([a-zA-Z0-9)]){3,}
code how looks like
var result="stackoverflow";
var string="22342st";
var res = string.match(/([a-zA-Z0-9)]){3,}/g);
if(res!=null){
//here what you want
}
I'm trying to reverse random int in JavaScript. I'm using this code:
'use strict';
function reverse_a_number(n)
{
n = n + '';
return n.split('').reverse().join('');
}
print(reverse_a_number(+gets())); //**+gets()** is like scanner.nextInt in Java and **print();** work's like console.log(); in JS.
This work well if number are not a big integer.
For the first test in my judge, code works correctly:
Input Output
256 652
123.45 54.321
But for BI i get Wrong Answer:
Maybe the best way is to cast array to string... Any suggestions?
The reason is that you cast your get() input to number. Don't do this, use a string as, I think, you receive it. Example:
'use strict';
function gets() {
return '52387456983765.98364593786'
}
function reverse_a_number(n)
{
n = n + '';
return n.split('').reverse().join('');
}
console.log(reverse_a_number(+gets())); // "489.56738965478325"
function reverse_a_number_new(n)
{
return n.split('').reverse().join('');
}
console.log(reverse_a_number_new(gets())); // "68739546389.56738965478325"
To read more about floats in JS: https://javascript.info/number#imprecise-calculations
function reverseNum(n){
var reverse = 0
while(n!=0) {
var rem = n%10
reverse = reverse*10 +rem
n = parseInt(n/10)
}
return reverse
}
reverseNum(523)
I have a string which is a car number plate. But for display purposes I what to add a space after the fourth char in this string. The data comes from a data service so I have to do this on the front-end
eg. AF13BXP to this AF13 BXP
The code below doesn't seem to work:
var $regtext = $('#regNumber');
if ($regtext.length > 0)
{
var regtext = $regtext.text(),
newRegtext = regtext.replace(/[\n\s]/g, '');
console.log(newRegtext);
}
Simple and clear way to do this, without regex:
var $regtext = $('#regNumber');
if ($regtext.length > 0)
{
var regtext = $regtext.text(),
newRegtext = regtext.substr(0, 4) + " " + regtext.substr(4);
console.log(newRegtext);
}
It's also pretty fast too: runs 10,000 times in 351ms, faster than splitting and joining etc. Good if you'll be processing loads of data from the webservice.
You can use following jquery : Demo
$('.test').keyup(function() {
var foo = $(this).val().split(" ").join("");
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,4}', 'g')).join(" ");
}
$(this).val(foo);
});
If you want to use regex the following should do it.
newRegtext = regtext.replace(/^(.{4})/,'$1 ')
Try this code
$(document).ready(function(e) {
var $regtext = $('#regNumber');
var $regtext = $regtext.text();
if ($regtext.length > 0)
{
regCheck = /^([A-Z1-9a-z]{1,4})([A-Z1-9a-z]*)$/;
regtext = regCheck.test($regtext);
newRegtext = $regtext.replace(regCheck,"$1 $2");
alert(newRegtext);
}
});
I've done some digging on the above topic but am now more confused than when I started.
I have a unit converter that I'm working on.
It's working fine as a base model but I'm now trying to make it more modular.
There are many units and many conversions.
My plan is to have a function that determines what type of conversion is required, temperature, area etc etc, that can then call the appropriate function to carry out the math.
I'm very new to JS which isn't helping matters as it could be a simple mistake that I'm making but it's just as likely that I'm getting huge errors.
I think the problem is passing the object to the next function and then using it.
I've played with the code a great deal and tried many different suggestions online but still no success.
here is my code:
<script type="text/javascript">
function Convert(from, to, units, res){
this.from = from;
this.to = to;
this.units = units;
this.res = res;
}
Convert.convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(this.units.val());
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Convert.prototype.convertTemp = function(){
var result = "invalid input";
var input = parseInt(this.units.val());
var f = this.from.val();
var t = this.to.val()
if(!isNaN(input)) {
if(f == "degC"){
if(t == "degF"){
result = input * 1.8 + 32;
}
if(t == "kelvin"){
result = input + 273.15;
}
}
}
console.log('Parsed input is', input, "and result is", result);
this.res.val(result);
return result;
}
//var calcTempTest = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
//var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
$("#btnConvert").click.convertUnits();
</script>
The first obvious problem is this line:
$("#btnConvert").click.convertUnits();
This tries to call a convertUnits() method defined on the click method of the jQuery object returned by $("#btnConvert"). There is no such method, so you get'll get an error about how click has no method 'convertUnits'.
What you want to be doing there is binding the convertUnits() function as a click handler, which you do by passing it to the .click() method as an argument:
$("#btnConvert").click(Convert.convertUnits)
It doesn't make sense to have declared convertUnits() as a property of Convert(), though, so (although it will work as is) I'd change it to just be:
function convertUnits() {
// your code here
}
$("#btnConvert").click(convertUnits);
The only other thing stopping the code working is that on this line:
var input = parseInt(this.units.val());
...you use this assuming it will be a Convert object with a units property but you haven't yet created a Convert object - you do that inside the if(measurementType == "temp") block with this line:
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
So move that line to the beginning of the function and then use test instead of this:
function convertUnits(){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(test.units.val());
if(measurementType == "temp"){
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Working demo: http://jsfiddle.net/jT2ke/
Some unrelated advice: parseInt() doesn't really make sense for a number to feed into your converter, because the user might want to enter decimal values. You can use parseFloat() instead, or the unary plus operator:
var input = +test.units.val();
But if you want parseInt() it is generally recommended to pass it a second argument to specify the radix:
var input = parseInt(test.units.val(), 10);
...because otherwise if the input text has a leading zero some browsers will assume the value is octal rather than base ten. (parseFloat() and the unary plus don't have that issue.)
I think you should not implement the method convertUnits inside Convert object. And the new code will look like the following:
convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Now you can initiate the convertUnits on the button click:
$("#btnConvert").click(function(){new convertUnits()});
I'm not sure if count is the right word to use because it doesn't really matter to me how many there are, but let me explain. My data will be formatted like this: (hi,(1,2),hey),(yo,(3,(rawr),4),howdy) and I have no control over how many dimensions there are. And I want to grab the lowest groups ["hi", Array[], "hey"] and ["yo", Array[], "howdy"] So if there was a way to "count" I could count the open parenthesis, and then count the closed ones and when it hits 0, that's when the regex ends. For example:
(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)
1---2---1----0-1---2--3----2--1------0
Now with that being said, I don't believe counting is possible but what I want is a subsitute solution. This is what I have so far /\([^\(]*?\)/ but that only returns the highest level group from each of the low-level groups aka (1,2) and (rawr).
You can use a stack to track the (and).
Array.reduce(
'(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)',
function(x,y){
if(y=='(')
return [x[0]+1, x[1]+(x[0]+1)]
else if(y==')')
return [x[0]-1, x[1]+(x[0]-1)]
else
return [x[0], x[1]+'-']
},
[0,'']
)[1]
Try it in firebug console.
This works for the original use-case and #Barmar's use-case - and it counts the parenthesis, if you really wanted that...
Also, I added arbitrary spaces all over the data strings - just in case (since you have no control over the incoming data)
var results = [];
var dataString = "(hi, (1,2) , hey), ( yo,( 3, ( rawr ), 4) , howdy )";
//var dataString = "(hi, (1 , 2 ), (3, 4), hey), (yo ,(3,(rawr ), 4), howdy)";
var dataSplit = dataString.split(",");
var trimRegex = /^\s+|\s+$/g;
var openParensRegex = /\(/;
var closeParensRegex = /\)/;
var parensRegex = /\(|\)/;
var parensCount = 0;
for (var x = 0, lenx = dataSplit.length; x < lenx; x++){
var cleanString = dataSplit[x].replace(trimRegex, "");
if (openParensRegex.test(cleanString)){ parensCount++; };
if (parensCount < 2){
results.push(cleanString.replace(parensRegex, "").replace(trimRegex, ""));
};
if (closeParensRegex.test(cleanString)){ parensCount--; };
};
console.log(results);
Hope that helps!
The following script might help, it will identify the parenthesis levels:
var string="(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)",i=0;
while (string.indexOf("(")>=0) {
i++;
string=string.replace(/\(([^()]+)\)/g,"|l"+i+"|$1|l"+i+"|");
}
Result:
|l2|hi,|l1|1,2|l1|,hey|l2|,|l3|yo,|l2|3,|l1|rawr|l1|,4|l2|,howdy|l3|
Fiddle: http://jsfiddle.net/GfUZh/
If you want to get the highest levels you can probably do it with regex by finding the intersection points, in this case ),(.
var str = '(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)';
var re = /(\(.+\)),(\(.+\))/;
var results = re.exec(str);
results.shift(); // remove first item which is useless
console.log(results); //=> ["(hi,(1,2),hey)", "(yo,(3,(rawr),4),howdy)"]
Demo: http://jsfiddle.net/elclanrs/fFmfE/