Using regex in javascript - javascript

I cannot get to work the following example of Regex in JavaScript. Regex is valid, was tested on some webs testing Regex expression.
I want it to check if input is in format: xxx,xxx,xxx.
It is alerting wrong input all the time. Thanks for any help.
var re = /[0-9a-zA-Z]+(,[0-9a-zA-Z]+)*/;
var toValidation = document.getElementsByName("txtSerial").value;
alert(toValidation);
if(!re.test(toValidation))
return true;
else
{
alert("Please insert valid text.");
return false;
}

document.getElementsByName("txtSerial") will return all elements by that name (node collection). Node collections do not have an attribute named value, thus, .value will be undefined (as can be seen by your alert).
Depending on your markup, you will want to use
document.getElementById("txtSerial")
or
document.getElementsByName("txtSerial")[0]
(although the last one is certainly not ideal).

Related

Match a decimal number and replace non numeric characters in javascript

I am using the the following function in javascript.
function chknumber(a) {
a.value = a.value.replace(/[^0-9.]/g, '', '');
}
This function replaces any non numeric character entered in a textbox on whose onkeyup i have called the above function. The problem is it allows this string as well
1..1
I want the function to replace the second dot character as well. Any suggestions will be helpful.
I don't advocate simplistically modifying fields while people are trying to type in them, it's just too easy to interfere with what they're doing with simple handlers like this. (Validate afterward, or use a well-written, thoroughly-tested masking library.) When you change the value of a field when the user is typing in it, you mess up where the insertion point is, which is really frustrating to the user. But...
A second replace can correct .. and such:
function chknumber(a) {
a.value = a.value.replace(/[^0-9.]/g, '').replace(/\.{2,}/g, '.');
}
That replaces two or more . in a row with a single one. But, it would still allow 1.1.1, which you probably don't want. Sadly, JavaScript doesn't have lookbehinds, so we get into more logic:
function chknumber(a) {
var str = a.value.replace(/[^0-9.]/g, '').replace(/\.{2,}/g, '.');
var first, last;
while ((first = str.indexOf(".")) !== (last = str.lastIndexOf("."))) {
str = str.substring(0, last) + str.substring(last+1);
}
if (str !== a.value) {
a.value = str;
}
}
Can't guarantee there aren't other edge cases and such, and again, every time you assign a replacement to a.value, you're going to mess up the user's insertion point, which is surprisingly frustrating.
So, yeah: Validate afterward, or use a well-written, thoroughly-tested masking library. (I've had good luck with this jQuery plugin, if you're using jQuery.)
Side note: The second '' in your original replace is unnecessary; replace only uses two arguments.
try with match method if your input is "sajan12paul34.22" the match function will return a array contain [12 , 34.22]
the array index [0] is used for getting first numeric value (12)
function chknumber(a) {
a.value = a.value.match(/[0-9]*\.?[0-9]+/g)[0];
}

how to use regex with user input variable

I am getting an array of objects using JSON and then my goal is to let the user search for a specific login. For this I want them to be able to type a letter and check each object login, if the letter is contained I want to display it.
In order to achieve this I worked on the following code:
var i;
var out="";
var exp=/d/g;
var result = " ";
for(i=0;i<users.length;i++){
result= exp.test(users[i].login);
if(result){
out+= users[i].login+ " ";
}
}
It works fine if I write the regex (in this case d) but once I try putting a variable inside the regex it wont work. How do I create a regex that will take the users input and work with the test function to perform the same task? Or idk if there is a better/more elegant solution for this. I know there are different regex questions already but I didn't find one that helped me.
Appreciate the help!
You're testing a literal string - that string is passed in by the user but it's still literal, not a regex.
So you should try:
if( users[i].login.indexOf(userInput) > -1)
This will pass if the given input is in the searched string.

Slicing a string from a textbox

I am trying to take a string entered by user from a textbox. Check the length of that string and if the string is over a given number perform the slice operation on it.
Here's what I came up with but my code does nothing. Checked console, no errors given.
html:
<form id="slice">
Enter a pharse:<input type="text" id="text_box_2"><br>
<input type="button" value="slice" onclick="Slice()">
Result: <input type="text" id="slice_result"><br>
</form>
Javascript function:
function Slice(){
var UserString = document.getElementById("text_box_2").value;
var UserStringValue = UserString.length;
var Result = Userstring.slice(1,6);
if (UserStringValue > 6){
document.getElementById("Slice_result").value = Result;
}
else{
alert("Please enter a longer phrase.")
}
}
what or where did I go wrong?
Be mindful of case-sensitivity.
This:
var Result = Userstring.slice(1,6);
Should be using UserString (capital "S") as defined earlier in your code.
Next, the input ID should be all lowercase, slice_result, to match to HTML, but your code uses different casing:
document.getElementById("Slice_result")
Here's a working JSBin with these fixes.
EDIT: As JaromandaX mentioned in the comments, if you want to take the first 6 characters you should use slice(0, 6).
from cursory reading of your code. it seems caused by this line
var Result = Userstring.slice(1,6);
and also this one
document.getElementById("Slice_result").value = Result
it should be
var Result = UserString.slice(1,6);
and
document.getElementById("slice_result").value = Result
Usually use of the following
var Value = $('#input_id').val();
will pull the requested information for you.
You can also set up arguments for your slice function and pass in the value when you run onclick();
I'd also note that slice() is a current js function, though your implentation with the capital 'S' is some what different, it may be better practice to change that name a bit.

Javascript contains statement

I'm trying check a field in a database to see if it does not contain either "UK_CONTACTS or a blank. If it is either of these conditions I want to copy the that field to another field. I am very very new at this and have come up with the following and have written in text "does not contain" as I don't know the correct syntax for javascript.
function getdbasename(){
var dbasedata = document.forms[0]._dbase_name.value;
}
If (dbasedata does not contain "UK_CONTACTS" || dbasedata does not contain " ") {
_area.value = _dbase_name.value;
}
Probably miles out but it's my best shot.
I think you want indexOf(). If dbasedata.indexOf(someString) is anything but -1, it contains someString.
You'll need the indexOf('what you need to check for') function on the string you want to check.
E.g. (field.value.indexOf('myvalue') > 0) will be true if field.value contains the term 'myvalue'

Detect Once a Certain Word Has Just Been Entered in a Textarea

Considering features like EditArea's and CodeMirror's autocomplete, I was wondering if, like Dreamweaver, there is a way to detect if the last word you entered is in a certain list then provide the same kind of suggestion box but with the function's arguments. I imagine you would use a regular expression on the entire field or possibly split() the whole thing (or the current line) then use the length attribute of the array to find the last bit of text, then do something involving an indexOf-like operation; however, this seems like it would get a bit resource-intensive. It almost looks like I've answered my own question, but it always helps to fully explain one's quandary, especially publicly. There's gotta be a better solution than mine. I appreciate any input. Thank you.
Put the list of words to match in an object, have the text or options to display as the value. Then on keyup or keypress you can get the last word of the text area using a function like:
function showLastWord(id){
var el = document.getElementById(id);
var lastWord = el.value.match(/\w+$/);
return lastWord? lastWord[0] : '';
}
Then check if the word is in the list and do stuff appropriately.
Edit
A small example is:
<textarea onkeyup="showHelp(this);"></textarea>
<script>
var getLastWord = (function() {
re = /\w+$/;
return function (s){
var lastWord = s.match(re);
return lastWord? lastWord[0] : '';
}
}());
var keyWords = {foo:'foo was typed',bar:'bar was typed'};
function showHelp(el) {
var lastWord = getLastWord(el.value);
// Check for matching own property of keyWords
if (keyWords.hasOwnProperty(lastWord)) {
// Do stuff
console.log(keyWords[lastWord]);
}
}

Categories