I want create simple AI for youtube in javascript. I want to write into input string like "Find Pranks on youtube". And that word "Prank" is variable... Everyone can write whatever thay want,but it must be sentence "Find 'something' on youtube". I tried to create regex, but it's to hard for me. Is it posible to do this like that?
The regex I tried is: \\Find\s\[abc]\s\\on\\youtube/i;
HTML Code:
<input type="text" id="uq" class="input auto-size"/>
<button id="button" onclick="question();" class="button" href="javascript:;">Ask</button>
Javascript Code:
function question()
const findonyoutube = /(?<=find)(.*)(?=on youtube)/gm;
var str = document.getElementById('uq').value;
if(findonyoutube.test(str))
{
alert(findonyoutube.exec(str)[0]);
}
}
Not working, it return Uncaught TypeError: Cannot read property '0' of null
To capture anything in between two words you can use:
function getVariable() {
const regex = /(?<=Find)(.*)(?=on youtube)/i;
let input = document.getElementById('myInput').value;
let match = regex.exec(input);
if(match) {
document.getElementById('debug').innerHTML = match[0];
return match;
} else {
return -1;
}
}
<h4>Example: Find ponies on youtube</h4>
<input type="text" id="myInput" />
<button onclick="getVariable();">Get Variable</button>
<br><br><hr>
<h3 id="debug"></h3>
It uses a positive lookahead and lookbehind to achieve this.
Related
<input id="myInput" onblur="myFunction()">
<script>
function myFunction() {
var value= document.getElementById('myInput').value;
var regexCharacter = /[0-9|,]+/g;
strFirst = value.replace(regexCharacter, '')
document.getElementById('myInput').value = strFirst
}
</script>
I want to replace '' when the input does not match the regex's.
My regex just allow input number and comma.
My function is replace when input matching, i want to replace when it's not matching.
E.g a12,b2a => 12,2
can anyone help me, thanks.
Use /[^0-9|,]+/g as your regex. The ^ mark is used to match any character that's not in range.
Pro tip: You dont have to memorize all these tokens, just use a tool like https://regex101.com/
First of all, your function is not called to check the value with reqex.
then yout reqex replace "" when is number not charactors
<input type="text" id="myInput">
<script>
myInput.addEventListener("input", function (e) {
var value= document.getElementById('myInput').value;
strFirst = value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1')
document.getElementById('myInput').value = strFirst
});
</script>
in this code you can write number whith dot
whith this reqex
value.replace(/[^0-9.]/g, '').replace(/(..?)../g
I think you should edit your regex to match letters instead of numbers. Like this: /[a-zA-Z|]+/g
I have this simple function to find and replace text in my textarea message. User will be able to type into the textarea and also be able to find and replace words from the text area they just entered. Currently I'm trying to use a while loop to replace multiple same words found in the textarea that the user keyed in. But every time I run it it seems to freeze the entire html page any idea why this is happening?
find and replace are textbox for user to key in the word they want to find and replace the user is able to key in multiple words to replace as well.
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message').value;
var lmao = message.indexOf(find);
while (message.indexOf(find) != -1) {
document.getElementById("message").value = message.replace(find, replace);
}
}
Replace while loop with a replaceAll.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message').value;
var lmao = message.indexOf(find);
document.getElementById("message").value = message.replaceAll(find, replace);
}
<div>Find <input id="find" value="find" /></div>
<div>Replace <input id="replace" value="replace" /></div>
<div>
<textarea id="message" style="height: 100px">you can find and replace every words just by .replaceAll, example: find 1 find 2 find 3</textarea>
</div>
<div>
<button onclick="findText()">Submit</button>
</div>
Just a addition in other answer you can use g for global search and to replace where you find that word .
Read more about regex and //g here
Also you can let the search case-insensitivity using i along with g like this :
message.replace(/find/g, replace)
This way it will also replace Find finD FIND
And instead of using while you can use if loop
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message').value;
var lmao = message.indexOf(find);
if(message.indexOf(find) != -1) {
document.getElementById("message").value = message.replace(/find/g, replace);
}
}
<div>Find <input id="find" value="find" /></div>
<div>Replace <input id="replace" value="replace" /></div>
<div>
<textarea id="message" style="height: 100px">you can find and replace every words just by .replaceAll, example: find 1 find 2 find 3</textarea>
</div>
<div>
<button onclick="findText()">Submit</button>
</div>
The issue is with your while condition. When all input fields are empty your while condition is true. So inside the while condition the input value keeps on updating to empty string again, which makes loop an infinite loop. Thats why your ui is breaking.
Issue Scenario
console.log(("").indexOf("") !== -1);
To fix this, you have to make sure that your find and replace values are not same. Or else, it will be an infinite loop again.
Fixed Solution
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message');
while (find !== replace && message.value.indexOf(find) != -1) {
message.value = message.value.replace(find, replace);
}
}
<input type="text" id="find">
<input type="text" id="replace">
<textarea name="" id="message" cols="30" rows="10"></textarea>
<button onclick="findText()">Check</button>
I'm trying to make a validation for my form with JavaScript. This is what I have done so far, and it works, but in the input "klassekode" needs to start with two letters and then one number.
My html code
<form class="form1" method="POST" id="registrerFagSkjema" action="registrerklasse.php" name="registrerFagSkjema" onSubmit="return validerRegistrerFag()">
Registrer klasse <br> <br>
Klassekode <br>
<input value="" type="text" name="fagkode" id="fagkode" onFocus="fokus(this)"
onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()"
onChange="endreTilStoreBokstaver(this)"/ /><br>
Klassenavn <br>
<input value="" type="text" name="klassenavn" id="klassenavn" onFocus="fokus(this)"
onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()" />
<input value="Registrer Klasse" type="submit" name="submit" id="submit" >
<input type="reset" value="Nullstill" id="reset" name="reset" onClick="fjernMelding()">
</form>
<div id="melding"></div>
My JavaScript code
function validate()
{
var klassekode = document.getElementById("klassekode");
var klassenavn = document.getElementById("klassenavn");
var feilmelding="";
//var firstTwoLetters = document.getElementById("klassekode").substring(0,2);
if(klassekode.value.trim()=="")
{
//alert("blank");
feilmelding="Fyll ut Klassekode";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassekode.style.border = "solid 1px red";
return false;
}
else if ( klassekode.value.trim().length!=3)
{
//alert("klassekode for lang");
feilmelding="Klassekode må kun være 3 bokstaver";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassenavn.style.border = "solid 1px red";
return false;
}
else if (klassenavn.value.trim()=="" )
{
//alert("blank");
feilmelding="Fyll ut Klassenavn";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassenavn.style.border = "solid 1px red";
return false;
}
else { return true;}
}
You got the hang of substring, and you can use that the newer method isNaN (Not a Number) and divide your third character with 1. If it's a letter, isNaN will return "true" and if it's a number, it will return "false".
I would, however, recommend you to learn regular expressions, as it will benefit you tremendously in the future.
You basically create a pattern and then test a string against that pattern. If you find a match, then it's correct. I made a snippet below to demonstrate:
function validateInput() {
let inputElement = document.getElementById("namn");
let divElement = document.getElementById("comment");
var message = "not true";
let inputValue = inputElement.value.trim();
let pattern = new RegExp(/^[a-zøæ]{2}\d{1}/, "i");
if (isValid(inputValue, pattern)) {
message = "true"
}
divElement.innerHTML = message;
}
function isValid(str, pattern) {
return str.match(pattern);
}
<input id="namn" type="input" value="">
<input type="button" onclick="validateInput()" value="Validate" />
<div id="comment"></div>
This row needs explanation:
let pattern = new RegExp(/^\d{1}[a-zøæ]{2}/, "i");
The regular expression contains expressions that can be stringed together:
^: start at the beginning of the string.
[a-zøæ]{2}: 2 characters must be between a-z or contain ø or æ.
\d{1}: next following 1 character must be a digit.
The flag "i" makes the a-z case insensitive. Another way would be to don't add a flag, and instead write [a-zA-ZøØæÆ]
Regex to the rescue. You can add another else if statement as per the following:
else if (klassekode.value.trim().length !== 3) {
// after checking whether the string length is 3 characters...
} else if (!klassekode.value.trim().match(/^[a-z]{2}\d/i)) {
// apply validation warning styles
return false;
}
An explanation of the Regex:
^ - asserts position at the start of the string
[a-z] - matches an alphabetic character
{2} - matches exactly twice
\d - matches a digit (0-9) once
i - case insensitive match
I am not checking the string length again because your previous condition accounts for it.
Ensure to trim() the value before using it (e.g. before sending it to the backend for processing, etc.), because otherwise the leading/trailing spaces will be retained.
This is a JavaScript problem...
I am trying to return exact case insensitive matches. For example, if I enter "yo" in the input box, I want it to return as true, which it does in my current approach, but it will also return true for anything ending or starting with "yo" (i.e. your). I still want cases like "Yo!" and "yo, what's up" to return true.
I've tried startsWith() and endsWith(), but I'm not really sure where to go with this...
<!DOCTYPE html>
<html>
<body>
<input type="text" id="input1">
<button type="submit" onclick="myFunction()">Test</button>
<p id="demo"></p>
<script>
function myFunction() {
var arr1 = [/hello/i, /\bhi/i, /\bhey/i, /yo/i];
var b = document.getElementById("input1").value;
document.getElementById("demo").innerHTML = arr1.some(regexp => regexp.test(b));
}
</script>
</body>
</html>
I want to get exact matches for words, as opposed to just a string.
I believe you are in your way using \b Word Boundaries, but you have an incorrect usage of they. If you read the docs, you need to wrap the word you want to match, by the \b metacharacter, like \bhello\b. Give a try to next example:
function myFunction() {
var arr1 = [/\bhello\b/i, /\bhi\b/i, /\bhey\b/i, /\byo\b/i];
var b = document.getElementById("input1").value;
document.getElementById("demo").innerHTML = arr1.some(regexp => regexp.test(b));
}
<input type="text" id="input1">
<button type="submit" onclick="myFunction()">Test</button>
<p id="demo"></p>
Is there a quick javascript library or code that would only allow a user to start a form input with a preset selection of words?
For example it would allow a user to start a the word "Are" or "What" but not "Why".
You can use the following Regex. (This is really primitive and should be improved according to your case.)
^(Why|Are).*$
HTML5 input pattern example:
<form>
<input type="text" pattern="^(Why|Are).*$">
<input type="submit">
</form>
Test here.
You can add change or input event listener to it and validate the content. To avoid false negatives with initial few letters you can start checking after the input string contains a space. You don't need a library to do that. Plain old JS will do the job.
var input = document.getElementById("myinput");
input.addEventListener('input', validate);
function validate(e) {
var validStart = ['why', 'when'];
var tmpVal;
if (this.value.indexOf(' ') !== -1) {
tmpVal = this.value.toLowerCase().trim();
if (validStart.indexOf(tmpVal) === -1) {
input.classList.add('notvalid');
} else {
input.classList.remove('notvalid');
}
} else {
input.classList.remove('notvalid');
}
}
JSFiddle: http://jsfiddle.net/ofx2yhzm/1/
Very similar to Strah's answer, but here it is anyway:
function checkValue(el) {
// Trim only leading whitespace so responds when first space entered
// and break into words
var words = el.value.replace(/^\s+/,'').split(/\s+/);
// List of allowed words
var allowed = ['are','what'];
// Element to write message based on source element
var msg = document.getElementById(el.id + 'Msg');
// Clear error message by default
msg.innerHTML = '';
// Only do something if at least one word has been entered
// Could also check if first word has more letters than
// longest allowed word
if (words.length > 1) {
// Check if first word is allowed
if ( allowed.indexOf(words[0].toLowerCase()) == -1) {
msg.innerHTML = 'Input must start with one of ' + allowed.join(', ');
}
}
}
Some markup:
<input id="foo" oninput="checkValue(this);">
<span id="fooMsg"></span>
This allows the user to at least enter a word before being given an error. They should also be given some onscreen hints to let them know which words to use, rather than having to get it wrong first (which is bound to happen a lot).
Html:
<form name="myform" method="post" action="#" onsubmit="return validate()">
<input type="text" name="val" />
<input type="submit" value="Submit" />
</form>
Javascript:
window.validate = function(){
data = document.forms['myform']['val'].value;
var starts = ['hi','he'];
for (var i = 0; i <= starts.length; i++)
if (data.indexOf(starts[i]) === 0) return true;
return false;
}
And of course you could also use Regex tho I guess that's a little more inefficient.
Something like this?: http://jsfiddle.net/4jasrbob/