Check a combination of string and integer using regex - javascript

I am trying to take input from the textbox now I want to show an alert if the textbox value matches with the regular expression.
I want to check "1702, Belgium" or "Belgium, 1702" using regex but I am getting null.
<script>
$(document).ready(function(){
var r =/+{1702}/;
var v=$(".a").val();
alert(v.match(r));
});
</script>
<body>
<input type="text" class="a" value="1702 Belgium"/>
</body>

Since we have only 2 strings need to be compared, Why cant we compare with array of constants("1702, Belgium" and "Belgium, 1702") instead of using regular expressions.
Comparing to regular expressions the above way is easy to understand.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var valuesToCompare = ["1702, Belgium", "Belgium, 1702"]
var v = $(".a").val().trim();
alert(valuesToCompare.includes(v));
// we can also use indexof to check
// alert(valuesToCompare.indexOf(v) !== -1);
});
</script>
<body>
<input type="text" class="a" value="1702, Belgium"/>
</body>

Consider the following example.
$(function() {
$("input.a").next("button").click(function(event) {
var currentValue = $("input.a").val();
var currentIndex = currentValue.indexOf("1702")
if (currentIndex >= 0) {
alert("1702 Found at " + currentIndex);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="a" value="1702 Belgium" /> <button>Check</button>
The .indexOf() will give you the position in the String that your string exists. It does the same for an Array. I have moved the code into a Click callback so you can test other strings or check it after something has been changed.

Related

Variable multiplier

I have created a simple calculator that takes variable #1 and variable #2 and multiplies them to generate a result.
When I change variable #1 the result instantly changes. However, when I change variable #2 the result remains unchanged.
How do I reconfigure my code so that the result instantly changes when either variable is altered?
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">
<h6>Variable #2</h6>
<input id="var2">
<h6>Result</h6>
<input readonly="readonly" id="result">
<script>
$(document).ready(function(){
var mt=$("#var1");
mt.keyup(function(){
var total=isNaN(parseInt(mt.val()* $("#var2").val())) ? 0 :(mt.val()* $("#result").val())
$("#result").val(total);
});
});
</script>
You have many things going wrong here,
you need to bind keyup event in var1 textbox and var2 textbox both
Also, your multiply formula is also wrong. Here is the desire code:
$(document).ready(function(){
var mt=$("#var1,#var2");
mt.keyup(function(){
debugger;
var total= 0;
if(!isNaN(parseInt($("#var1").val())* parseInt(parseInt($("#var2").val())))){
total= parseInt($("#var1").val())* parseInt(parseInt($("#var2").val()));
}
$("#result").val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">
<h6>Variable #2</h6>
<input id="var2">
<h6>Result</h6>
<input readonly="readonly" id="result">
Consider binding keyup events on both #var1 and #var2 inputs using the following jQuery syntax #var1, #var2 to achieve this desired behaviour, as shown:
$(document).ready(function(){
// Select and bind keyup event to both "var" input elements using
// this syntax
$('#var1, #var2')
.keyup(function(){
// Adjust your keyup handler to perform calculation when keyup
// occurs on either input field
var total= 0;
if(!isNaN(parseInt($("#var1").val())* parseInt($("#var2").val()))){
total = parseFloat($("#var1").val())* parseFloat($("#var2").val());
}
$("#result").val(total);
});
});
I just want to answer in vanilla Javascript for future reference of the problem..
I make var1,var2 class="input", then querySelect them both, then loop them, so that when you put any number to them, their value(product) will be produce in the id="result"
if you did not put any number to them, the default value is zero(0) for both of them, so let say, you only put 10 to var1, then the output will only be 10, and if you put non numeric character, then the output is NaN.
let input = document.querySelectorAll(".input");
let var1 = document.querySelector("#var1");
let var2 = document.querySelector("#var2");
let output = document.querySelector("#result");
function result(var1=0,var2=0) {
output.value = Number(var1)*Number(var2);
}
for(let i=0;i<input.length;i++)
{
input[i].addEventListener(`keyup`,()=>result(var1.value,var2.value))
}
<h6>Variable #1</h6>
<input id="var1" class="input">
<h6>Variable #2</h6>
<input id="var2" class="input">
<h6>Result</h6>
<input readonly="readonly" id="result">
By the way you can also make the code much shorter by instead of putting the id var1,var2 value, you can instead just put the input class[0], and [1] it's the same..
so it can also be done this way.
let input = document.querySelectorAll(".input");
let output = document.querySelector("#result");
function result(var1=0,var2=0) {
output.value = Number(var1)*Number(var2);
}
for(let i=0;i<input.length;i++)
{
input[i].addEventListener(`keyup`,()=>result(input[0].value,input[1].value))
}
<h6>Variable #1</h6>
<input id="var1" class="input">
<h6>Variable #2</h6>
<input id="var2" class="input">
<h6>Result</h6>
<input readonly="readonly" id="result">
By the way if you want to follow the same logic by using ternary operator,
let's follow his example, by using ternary operator,
change the result function to this.
function result(var1=0,var2=0) {
(var1*var2 ===0)? output.value=0: output.value=Number(var1) * Number(var2);
}

Get value from hidden field - JavaScript

I have a <input type="hidden" class="Key" value="1m2.123.mds.34g" />
How can I get the value without using jQuery?
With jQuery i just only write:
var parse = $('.Key').attr("value")
alert(parse);
I need this in pure JavaScript, maybe use RegEx? I will execute this script on txt file which will contain such line.
check this
window.onload=function(){
var hidden=document.getElementsByClassName("Key");
alert(hidden[0].value);
}
<input type="hidden" class="Key" value="1m2.123.mds.34g" />
var inputs = getElementsByClassName('Key');
for(var i=0; i<inputs.length;i++) {
console.log(inputs[i].value);
}
Easy! Just use getElementsByClassName. E.g:
document.getElementsByClassName('Key')[0].value
Or if you had to get the value by id you can use getElementById
document.getElementById('idHere').value
Here's 4 ways to get the value of .Key. Also I added a better way to do it in jQuery as well using the method val().
SNIPPET
var k = document.querySelector('.Key').value;
console.log(k);
// This works if .Key is inside a <form>
var e = document.forms[0].elements[0].value;
console.log(e);
var y = document.getElementsByTagName('input')[0].value;
console.log(y);
var s = document.getElementsByClassName('Key')[0].value;
console.log(s);
//BTW there's a better way of finding value with jQuery
var $Key = $('.Key').val();
console.log($Key);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='f1'>
<input type="hidden" class="Key" value="1m2.123.mds.34g" />
</form>
Thank you all. I resolve this problem as follow:
var regEx = /class="Name"+ value="(.*?)"/;
newName = result.match(regEx)[1];
var regEx2 = /class="Key"+ value="(.*?)"/;
var key = result.match(regEx2)[1];
Alert(key + ' ' + newName );

Removing last word from an input value

I've been trying to remove the last word of an input value using the following code:
$('#buttonid').on('click',function () {
var textVal = $('#inputid').val();
$('#inputid').val(textVal.substring(0,textVal.length - 1));
});
This code removes only one letter from the word. I know I can delete the whole word by specifying the number of its letter in textVal.length - 1. However, the word is not static, so I want to use something that removes any last word in the input value.
Edit, Note: Words are separated by dots, not spaces.
Any suggestions?
You can use lastIndexOf method to find a position of the last dot separating last word:
$('#buttonid').on('click', function () {
var textVal = $('#inputid').val();
$('#inputid').val(textVal.substring(0, textVal.lastIndexOf('.')));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonid">Remove</button>
<input type="text" id="inputid">
You can also make your code a little cleaner if you don't reselect the same element again but use a function in the val method:
$('#buttonid').on('click', function () {
$('#inputid').val(function() {
return this.value.substring(0, this.value.lastIndexOf('.'));
});
});
Bonus point. If you want you can use very simple regular expression (although it might be overkill here, but regexp is more reliable then '.' in lastIndexOf) to remove everything after the last word boundary, for example:
$('#inputid').val(function() {
return this.value.replace(/\b.\w*$/, '');
});
Use lastIndexOf(' ') instead of length - 1. The former will take the last index of a space (which signifies the last word, barring any edge cases you may have) and use it as the end point for your substring.
The latter is supposed to only give you the index of the last letter, since calling textVal.length would result in the number of actual characters in the string, not words.
$('#inputid').val(textVal.substring(0, textVal.lastIndexOf(' '));
Another option would be to transform the text to an array, and pop() it, to remove the last element. Then, rejoining it using space as a separator.
$('#buttonid').on('click', function () {
var textVal = $('#inputid').val().split(' ');
textVal.pop();
$('#inputid').val(textVal.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="inputid"></textarea><br>
<button id="buttonid">Remove Word</button>
You can use the lastIndexOf method to get the last index of occurring peroid. Here's the code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#buttonid").on('click',function ()
{
//get the input's value
var textVal = $('#inputid').val();
var lastIndex = textVal.lastIndexOf(".");
$('#inputid').val(textVal.substring(0,lastIndex));
});
});
</script>
</head>
<body>
<input type="button" id="buttonid" value="Go">
</input>
<input type="text" id="inputid" value="Anything.could.be">
</input>
</body>
</html>

Get a list of outputs with a while loop using javaScript

i m trying to get a list of outputs which doesn't divide evenly by number which are smaller than the input value.For example if the input value is 10,the list should be 10,9,8,7,6,4,3,1. below is my code and doesn't give me any output nor any error message.I m new to javascript and i need to know what i m doing wrong.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>An example of using "for" and "while" in PHP</title>
<script type="text/javascript">
function displayResult()
{
if(text_form.numberfield.value){
var number=document.getElementsByName("numberfield").value;
var div=document.getElementsByName("numberfield").value;
while (div>0)
{
if(number%div==0 && div!=number && div!=1)
{
div--;
continue;
}
if (div == 0)
{
break;
}
document.write(div--);
document.write(",");
}
}
else
{
document.write("Enter a number");
}
}
</script>
</head>
<body>
<H1>An example of using "for" and "while" in PHP</H1>
<form name="text_form">
Please input a number: <input type="text" name="numberfield"> </label>
<input type="submit" value="Submit" onclick="displayResult()" />
</form>
<p> Result is shown as below.</p>
</body>
</HTML>
getElementsByName returns an array, not an element.
Try:
var number=document.getElementsByName("numberfield")[0].value;
var div=document.getElementsByName("numberfield")[0].value;
Notice the [0]. You also have to modify a bit to make it work.
DEMO
the getElementsByName returns a list of elements having the specified name not a single element. You can access each element using loop:
var elems=document.getElementsByName("name")
for(var i=0;i<elems.length;i++){
var elem=elems[i]
//access each element using iterator
}
Also the getElementsByTagName returns a list of elements having the specified tag name.

Comparing similar strings in jquery

How do I compare similar strings in jquery?
<script src="../../js/jq.js"></script>
<script>
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase());
var str2 = $.trim($('#str2').val().toUpperCase());
if(str1==str2){
console.log('yep');
}
});
</script>
<input type="text" id="str1" value="One String"/>
<input type="text" id="str2" value="One String1"/>
Comparing "One String" and "One String1" is not going to work if I'm only checking if the two values are equal. Is there any way to do this in jquery? For example I only want to compare 90% of the string.
You can see if one is contained inside the other for example:
if (str1.indexOf(str2) >= 0 || str2.indexOf(str1) >= 0)
console.log('yep');
}
Check this out : http://jsfiddle.net/Sj5dE/ You can comment out a,b block to see the similitude of the strings. It's of course case-sensitive. I hope this helps. Since your example talked about comparing two similar strings, I thought it'd be most likely that the beginning of the strings are the same so I didn't introduce any substring logic but feel free to change the function.
Try this it might work
<script src="../../js/jq.js"></script> <script>
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase());
var str2 = $.trim($('#str2').val().toUpperCase());
if(str1===str2){ console.log('yep'); } });
</script>
<input type="text" id="str1" value="One String"/>
<input type="text" id="str2" value="One String1"/>
In javascript you can use the substring to get the 90% of the string you would like to compare.
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase().substring(0, 10);
var str2 = $.trim($('#str2').val().toUpperCase().substring(0, 10);
if(str1==str2){
console.log('yep');
}
look on
http://code.google.com/p/google-diff-match-patch/
the demo in
http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html
You can check if the string is present or not by
$(".className").replace(/(^|\s)yourTextHere\S+/g, " ");

Categories