I'm working on a textbot project, where if I input some text in a textbox, the bot spits out something in the console, fairly simple. However, I've run into a problem that I am very frustrated over, and haven't managed to solve. There's probably a simple solution to this, but I can't find it.
What I want to do, is having the textbox accept a command that consists of the user input + a variable that the user inputs. Something like this:
case "input " + condition {
//do something with condition
}
My question is how do I make the textbox differ between the input and the condition? I hope this question isn't way too hard to understand, but I don't know how else to explain it :P
Edit:
Example:
Textbox input:
"!locate p.actionValue"
Then depending on what actionvalue the person inputs, this should return something like:
if (actionvalue = 32) {
//do something if actionvalue is 32
}
But how do i differ between the command and condition?
You can use a regular expression to match the input and get the condition:
var match;
if (match = input.match(/^!locate (.*)/)) {
var condition = match[1];
// do something with condition
}
You can get more general:
var match = input.match(/^!(\S+)\s+(.*)/);
if (match) {
var command = match[1];
var arg = match[2];
switch (command) {
case 'locate':
...
break;
}
}
You can split your text by "input " and then you will get the command
// array separated by 'input '
var command = textbox.split('input ');
// here you got your command: command[0]
of course you'll need to validate that it actually has 'input ', and what happens in cases like 'input input '
Related
I started learning javascript, and I am trying to make a little project to play around.
I want to validate that the input field for username contains only letters (uppercase or lowercase) and when the value is correct, to outline the field with a color. (I don't care about the design, i care about functionality since it's purpose is for learning).
I have this code: https://jsfiddle.net/7zcv4g1m/1/
const userField = document.querySelector('#user .user');
const passwordField = document.querySelector('#password .password');
const regEx = /^[a-zA-Z]+$/g;
function checkUser() {
// userField.setAttribute('class', 'user');
let userText = userField.value.substring(0, userField.value.length);
let expr = regEx.test(userText);
if (expr == true && userText.length > 0) {
userField.setAttribute('class', 'user test');
} else {
userField.setAttribute('class', 'user');
}
}
userField.addEventListener("focusout", checkUser, false);
My problem is this: at first run, if I click on the element and type a correct text, it outlines the input as expected when I focusOut of the element. The issue is when I click back in the element and just click somewhere outsite of the element to trigger focusout event, without modifying anything in the text. Somehow, my regex condition (the expr variable in the code) is considered to be false, instead of being true, and it turn the element's output back to grey instead of green. If I click back in and after out, it turns back the input border to green.
I don't understand why is this happening and where I made a mistake. Or maybe I wrote the code wrong. If anyone can please give me a hint, will be much appreciated.
It's caused by regEx.test(userText). This should work:
function checkUser() {
// userField.setAttribute('class', 'user');
let userText = userField.value.substring(0, userField.value.length);
let expr = userText.match(regEx);
if (expr && userText.length > 0) {
userField.setAttribute('class', 'user test');
} else {
userField.setAttribute('class', 'user');
}
}
delete modificier g in RegEx, like as
const regEx = /^[a-zA-Z]+$/
Not certain if this can be done in regexp under javascript, but thought it would be interesting to see if it is possible.
So thought I would clean up a piece of html to remove most tags, literally just dropping them, so <H1><img><a href ....>. And that would be relatively simple (well, stole the basis from another post, thanks karim79 Remove HTML Tags in Javascript with Regex).
function(inString, maxlength, callback){
console.log("Sting is " + inString)
console.log("Its " + inString.length)
var regex = /(<([^>]+)>)/ig
var outString = inString.replace(regex, "");
console.log("No HTML sting " + outString);
if ( outString.length < maxlength){
callback(outString)
} else {
console.log("Lets cut first bit")
}
}
But then I started thinking, is there a way where I can control regex execution. So lets say that I want to keep certain tabs, like b,br,i and maybe change H1-6 to b. So in pseudo code, something like:
for ( var i in inString.regex.hits ) {
if ( hits[i] == H1 ) {
hits[i] = b;
}
}
The issue is that I want the text thats not HTML tags to stay as it is, and I want it to just cut out by default. One option would of course be to change the ones I want to keep. Say change <b> to [[b]], once that is done to all the ones of interest. Then put them back to <b> once all unknown have been removed. So like this (only for b, and not certain the code below would work):
function(inString, maxlength, callback){
console.log("Sting is " + inString)
console.log("Its " + inString.length)
var regex-remHTML = /(<([^>]+)>)/ig
var regex-hideB = /(<b>)/ig
var regex-showB = /([b])/ig
var outString = inString.replace(regex-hideB, "[b]");
outString = outString.replace(regex-remHTML, "");
outString = outString.replace(regex-showB, "<b>");
console.log("No HTML sting " + outString);
if ( outString.length < maxlength){
callback(outString)
} else {
console.log("Lets cut first bit")
}
}
But would it be possible to be smarter, writing cod ethat says here is a peice of HTML tag, run this code against the match.
As Tim Biegeleisen sai in its comment, maybe a better solution could be using a parser instead of a Regex...
By the way, if you want to control what is going to be changed by the regex you can pass a callback to the String.prototype.replace:
var input = "<div><h1>CIAO Bello</h1></div>";
var output = input.replace(/(<([^>]+)>)/gi, (val) => {
if(val.indexOf("div") > -1) {
return "";
}
return val;
})
;
console.log("output", output);
Is there a way to validate the text of the input textBox of the prompt box displayed by calling window.prompt() in javascript?
I mean something like to not to close the prompt box when clicking its OK button if the string written in its input textBox contains numbers or other illegal chars defined by me, etc.
No, there is not.
.prompt is native functionality that can't be modified.
If you want input validation, you're going to need to use a custom prompt. It might be worth looking into UI libraries like jQueryUI, for example.
var obj = {};
function validate( str ){
return !! str; //or your own validation
}
function setName ( error_message ) {
var name = prompt( (error_message || '') + "Enter a name: ");
if ( ! validate( name ) ) {
setName( 'Invalid name entered\n' );
} else {
obj.name = name;
}
}
If you really want to use only prompt then this is the solution. But, I'd suggest you to use a modal dialog or create your own component.
You can't validate the input of a prompt before closing it. You could simulate this by creating your own type of prompt, or using jQueryUI.
I came across this exact problem today while writing a bookmarklet which requests user input.
It struck me that it's possible to validate window.prompt simply by using a while loop:
let promptedAnswer = null;
while (promptedAnswer !== 'spoon') {
promptedAnswer = prompt('Complete this phrase: "There is no [ ]."');
}
Working Example:
let chosenNumber = 0;
while ((chosenNumber < 1) || (chosenNumber > 10)) {
chosenNumber = prompt('Choose a number between 1 and 10:');
}
console.log('Your chosen number is ' + chosenNumber);
I have a question. I'm wanting to run a basic function in Javascript which takes an input field from a form and checks the very first character to ensure it does not have a £ sign (GBP) infront of the value
I can't seem to find the right code anywhere to do this? - Anyone have any idea's... I'm a bit of a noob to all this programming to be honest so any help would be gratefully received.
If you have an input field and you want to get it's value and check the first character of the value, you can do so like this:
<input type="text" id="price">
var str = document.getElementById("price").value;
if (str.charAt(0) == "£") {
// do whatever you need to do if there's a £ sign at the beginning
}
If the £ sign isn't supposed to be there, perhaps you could just safely remove it or ignore it rather than make the end user remove it like this:
var el = document.getElementById("price");
if (el.value.charAt(0) == "£") {
el.value = el.value.substr(1);
}
Assuming your HTML is something like this:
<input type="text" id="my_input" />
<button onClick="checkInput();">Check input</button>
Then you want to build your script like this:
function checkInput() {
var inp = document.getElementById('my_input'); // get the input field
inp = inp.value; // get the value
inp = inp.charAt(0); // get the first character
if( inp == "£") {
// do something
}
}
That can be condensed into:
function checkInput() {
if( document.getElementById('my_input').value.charAt(0) == "£") {
// do something
}
}
The trick to any code-writing is breaking a big problem into smaller ones. Step by step.
charAt should do it
var str = "Foo";
var firstChar = str.charAt(0);
I am stuck in implementing the following:
User starts typing in a textbox.
The javascript on page captures the first character typed, validates that it is an english alphabet (a-z,A-Z) and converts it to lowercase (if necessary).
Make an XMLHttp request based on the input (i.e. if first input character is a, get a.xml, if b get b.xml and so on).
I know how to do the last part (make the xmlhttp request) but am kind of stuck on how to capture the first character and validate it (in a way that works on all browsers). Please guide. Thanks.
Clarification: This is to create a Google Suggest like autocomplete-drop-down menu without the need for server side programs.
Something like this should work:
HTML:
<input type="text" id="myField" />
And in JS:
window.onload = function() {
document.getElementById('myField').onkeyup = function() {
// Validate that the first letter is A-Za-z and capture it
var letter = this.value.match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
// Do the request
}
}
}
My vanilla-JS skills are a bit rusty but this should do the trick. Just for the heck of it, here's the same using jQuery:
$(function() {
$('#myField').keyup(function() {
var letter = $(this).val().match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
$(this).val(letter + $(this).val().substring(1);
// Do the request
}
});
});
What part of the problem do you not know how to do? Here's an approach that you can follow. Very likely to need adjustments, but a good starting point
if our text field's id is 'txt'
document.getElementByID('txt').onkeypress = function(e) {
var textInField = this.value;
if (textInField.length == 1) {
var firstChar = textInField.charAt(0);
if (/[a-zA-Z]/.test(firstChar)) {
sendXHR(textInField.value.toLowerCase())
}
} else {
// What do you do if there is one or more chars???
}
}
Note that the other answers here mention onchange, that doesn't fire until the focus leaves the field, which I don't think is what you want