Reputation: 1662
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>
Upvotes: 2
Views: 137
Reputation: 30893
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.
Upvotes: 0
Reputation: 2353
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>
Upvotes: 2