I'm definitely a newbie and am trying a practice project.
Its basically an anagram game where the user clicks on certain letters to put together a word.
I now need to check that it is actually a word. I've made a text file containing all the words in the dictionary (copied from someones website as its just a practice project). I've managed to get it so that if I can console.log the words.
function Searchtext(){
$.get('words.txt', function(data) {
console.log(data);
}, 'text');
}
Now I want to search the words to see if the player's answer ( a string which is declared in a variable called playeranswer ) is in the list. I don't need it to return the word, only whether it is there or not. N.B. it has to be exact so that for example if the user entered "ender" which isnt a word, it wont come back true because it finds the word "render". Maybe something with the .length will help?
How would I go about doing this?
Thanks for any help.
Since $.get is asynchronous, you'll have to set it up a little differently. I'd do this:
function Searchtext(name, callback) {
$.get('words.txt', function(data) {
data = data.split("\n");
var contains = (data.indexOf(name) > -1);
callback(contains);
}, 'text');
}
Depending on how the text file is setup, you might have to change .split("\n") (which splits up the words into an array, if they're each on a line) to .split(" ") (which splits up the words into an array, if they're separated by a space).
And you'd call it like:
SearchText(playername, function (matched) {
if (matched) {
// Name was in list
} else {
// Name wasn't in list
}
});
DEMO: http://jsfiddle.net/Fkr5B/
In the demo, I had to simulate the AJAX request.
I would use a regular expression (using a RegExp object) for this. Here is a simple example that tries to match a word in two different strings of words:
var word_to_match = 'ender';
var string_of_words = 'a string containing the word ender, this will match';
var second_string_of_words = 'a string that will not produce a match';
//use \b to match on word boundaries
var filter = new RegExp('\\b' + word_to_match + '\\b', 'gi');
if(string_of_words.match(filter)) {
alert('found word: ' + word_to_match);
} else {
alert('did not find word: ' + word_to_match);
}
if(second_string_of_words.match(filter)) {
alert('found word: ' + word_to_match);
} else {
alert('did not find word: ' + word_to_match);
}
You'll see the first if statement passes, while the second fails. A little reading might be required, but you should be able to expand this example to fit your use case.
You should first parse the data variable and place the words into an Array.
Then you can test if the user entered a valid word by checking if your Array contains that word.
var Dict = new Array("render", "bender", "word");
function isValid(word){
if(Dict.indexOf(word) == -1)
return false; //the word is not valid
return true; //the word is valid
}
I've made this simple script, hope it helps
$(document).ready(function(e) {
function parseData(data) {
$('#inpu').blur(function() {
var str_to_search = $.trim($('#inpu').val());
if(str_to_search.length) {
var search_res = data.search(str_to_search);
if(search_res != -1) {
alert('Word Valid!');
} else {
alert('Word no valid');
}
}
});
}
$.get('to_search.txt', parseData).fail(function() { alert('error');});
});
Related
First off, I am a complete noob. I have just recently started getting good with python and have close to zero knowledge regarding javascript and corvid for wix. I am looking through documentation but I can't figure out how to do the following: When a user fills out a field, let's say a phone number field, how do you validate whether that field has any alphabetical characters or "+" or "-" etc or not?
I am trying to do something like this:
$w.onReady(function () {
$w("#input1").onCustomValidation( (value, reject) => {
if( input1 is anything but an integer ) {
reject("Only Numbers. No '-', '.', '()', '+', or any alphabetical characters");
}
} );
});
I feel like I am close but have no idea. Any help is appreciated
To answer your question:
Includes Function
You would want to use the .includes() function native to javascript which returns a boolean of if it is or isn't included. If you need the string index of each occurrence you would need to use a for loop as shown below.
var string = "+54 2453-2534-242";
for(int i = 0; i < string.length(); i++){
if(string.substr(i,1) === "-"){
console.log(i);
}
}
Includes Function
Replace Function
Below is an example of how to use this function.
If you wish to remove these or one of these characters you can use the .replace() function or the .split() and .join() functions.
const string = "+53 573-2566-242";
const character_1 = "+";
const character_2= "-";
// Includes
console.log(string + ".includes(+):", string.includes(character_1));
console.log(string + ".includes(-):",string.includes(character_2));
// Replace Singular
var new_string = string.replace(character_1,'');
console.log(new_string);
// Replace Multiple
var new_string2 = string.split(character_2).join("");
console.log(new_string2);
Replace Funtion
If you are still stuck, please feel free to comment
Edit
To check if there are any alpha-numeric characters in a string. You can simply use the .replace() function and compare it. As seen below:
var string = "abc546"; // Your Phone Number Input
var string_converted = string.replace(/\D/g,'');
if(string !== string_converted){
console.log("Contains Characters that are not of type NUMBER!");
console.log(`${string} vs ${string_converted}`);
}
In your case, you could use the code below:
$w.onReady(function () {
$w("#input1").onCustomValidation( (value, reject) => {
// Assuing *value* is your input
var converted = value.replace(/\D/g,'');
if(value !== converted){
// Regective Statment Here..
}else{
// All good! (No Alph-numeric Characters)
}
});
});
How do I go about assigning certain words a unique id tag using vanilla javascript? For example:
<p>All the king's horses ran away.</p>
The word "All" gets the id "term1", "King's" gets "term2", "away" gets "term3", etc. but not every word in the sentence will get assigned an id.
I am currently using the replace method but I think it's the wrong approach:
var str = document.getElementsByTagName('p')[0].innerHTML;
function addId() {
txt = str.replace(/all/i, '<span id="term1">$&</span>').replace(/king's/i, '<span id="term2">$&</span>').replace(/away/i, '<span id="term3">$&</span>');
document.getElementsByTagName('p')[0].innerHTML = txt;
}
window.onload = function() {
addId();
};
<p>All the king's horses ran away.</p>
This forces me to chain a bunch of replace commands, changing the id name each time. I don't think this is the best solution. What is best way to do this? Thanks for your help!
I believe this should make the job done. You can replace blacklist with whitelist. That will depend on your use case. Also, addIds can use Array.map instead of Array.forEach that will make the whole function a one-liner. This example is imperative because it will be more readable.
// string - string where we want to add ids
// blackList - words we want to skip (can be whiteliste black list is more general)
function addIds(string, blackList = ['the', 'a']) {
const stringArray = string.split(' ') // split string into separate words
let stringWithIds = string // this will be final string
stringArray.forEach((item, index) => {
// skip word if black listed
if (blackList.indexOf(item.toLowerCase()) !== -1) {
return
}
stringWithIds = stringWithIds.replace(item, `<span id="term${index}">${item}</span>`) // add id to word if not black listed
})
// replace string with our string with ids
document.getElementsByTagName('p')[0].innerHTML = stringWithIds;
}
window.onload = function() {
const str = document.getElementsByTagName('p')[0].innerHTML;
addIds(str); // you can pass custom blacklist as optional second parameter
};
<p>All the king's horses ran away.</p>
I think this function would be flexible enough for the task:
// Here, your logic to decide if the word must be tagged
const shouldBeTagged = word => {
return true
}
function addId(str) {
// Split the string into individual words to deal with each of them
// one by one
let txt = str.split(' ').map((word, i) => {
// Should this word be tagged
if (shouldBeTagged(word)) {
// If so, tag it
return '<span id="term' + i + '">' + word + '</span>'
} else {
// Otherwise, return the naked word
return word
}
// Join the words together again
}).join(' ')
document.getElementsByTagName('p')[0].innerHTML = txt;
}
window.onload = function() {
addId(document.getElementsByTagName('p')[0].innerHTML);
};
<p>All the king's horses ran away.</p>
I'm currently working with Javascript and for now I'm searching a way to check if variable contains at least one string. I have looked at previous questions, however, neither contain what I'm looking for. I have a function here:
function findCertainWords()
{
var t = {Some text value};
if (t in {'one':'', 'two':''})
return alert("At least one string is found. Change them."), 0;
return 1
}
Variable a is user's written text (for example, a comment or a post).
I want to check if user has written certain word in it and return an alert message to remove/edit that word. While my written function works, it only works when user writes that word exactly as I write in my variable ("Three" != "three"). I want to improve my funtion so it would also find case-insensitive ("Three" == "three") and part of words (like "thr" from "three"). I tried to put an expression like * but it didn't work.
It would be the best if every expression could be written in one function. Otherwise, I might need help with combining two functions.
Use indexOf to test if a string contains another string. Use .toLowerCase to convert it to one case before comparing.
function findCertainWords(t) {
var words = ['one', 'two'];
for (var i = 0; i < words.length; i++) {
if (t.toLowerCase().indexOf(words[i]) != -1) {
alert("At least one string was found. Change them.");
return false;
}
}
return true;
}
Another way is to turn the array into a regexp:
var regexp = new RegExp(words.join('|'));
if (regexp.test(t)) {
alert("At least one string was found. Change them.");
return false;
} else {
return true;
}
You can use Array.some with Object.keys
if(Object.keys(obj).some(function(k){
return ~a.indexOf(obj[k]);
})){
// do something
}
I'm trying to write a function that checks a parameter against an array of special HTML entities (like the user entered '&' instead of '&'), and then add a span around those entered entities.
How would I search through the string parameter to find this? Would it be a regex?
This is my code thus far:
function ampersandKiller(input) {
var specialCharacters = ['&', ' ']
if($(specialCharacters).contains('&')) {
alert('hey')
} else {
alert('nay')
}
}
Obviously this doesn't work. Does anyone have any ideas?
So if a string like My name is & was passed, it would render My name is <span>&</span>. If a special character was listed twice -- like 'I really like &&& it would just render the span around each element. The user must also be able to use the plain &.
function htmlEntityChecker(input) {
var characterArray = ['&', ' '];
$.each(characterArray, function(idx, ent) {
if (input.indexOf(ent) != -1) {
var re = new RegExp(ent, "g");
input = input.replace(re, '<span>' + ent + '</span>');
}
});
return input;
}
FIDDLE
You could use this regular expression to find and wrap the entities:
input.replace(/&| /g, '<span>$&</span>')
For any kind of entity, you could use this too:
input.replace(/&(?:[a-z]+|#\d+);/g, '<span>$&</span>');
It matches the "word" entities as well as numeric entities. For example:
'test & & <'.replace(/&(?:[a-z]+|#x?\d+);/gi, '<span>$&</span>');
Output:
test & <span>&</span> <span><</span>
Another option would be to make the browser do a decode for you and check if the length is any different... check this question to see how to unescape the entities. You can then compare the length of the original string with the length of the decoded. Example below:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
function hasEntities(input) {
if (input.length != htmlDecode(input).length) {
return true;
}
return false;
}
alert(hasEntities('a'))
alert(hasEntities('&'))
The above will show two alerts. First false and then true.
I'm trying to do something that would be similar to turning a url slug-like variable into text that could be used for a title.
So, I have a variable for example that is like this:
var thisID = 'athlete-profile';
function myFunc(thisID) {
// i need to use thisID as the id and href in a loop that generates a string of <li><a>'s\
function makeTitle(thisID) {
// convert thisID to text so for this example it would return 'Athlete Profile'
return 'Athlete Profile';
}
for () {
var str = '<li id="'+thisID+'">'+makeTitle(thisID)+'';
}
// make sense?
}
I'd like to not use a regex to do this if possible somehow, but I don't think there's a way to do it without one. So any one who knows how to do this type of thing let me know, it would be a great help.
Thanks
I would advise you to use regular expression. But if you really don't want to use regular expressions, the solution below would work for simple cases. Feel free to modify it as you like it.
function makeTitle(slug) {
var words = slug.split('-');
for (var i = 0; i < words.length; i++) {
var word = words[i];
words[i] = word.charAt(0).toUpperCase() + word.slice(1);
}
return words.join(' ');
}
console.log(
makeTitle("athlete-profile")
)
function titleize(slug) {
var words = slug.split("-");
return words.map(function(word) {
return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
}).join(' ');
}
console.log(titleize("athlete-profile"))
It works pretty simply:
It splits the string by - into words.
It maps each word into title case.
It joins the resulting words with spaces.
Do it in one line:
'athlete-profile'.split("-").join(" ").replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()})
Output: Athlete Profile
The makeTitle() part of your question can be implemented something like this:
function makeTitle(thisID) {
return thisID.replace(/-/g, " ").replace(/\b[a-z]/g, function() {
return arguments[0].toUpperCase();
});
}
console.log(makeTitle("athlete-profile"))
The first .replace() changes all hyphens to spaces, and then the second .replace() takes any lower-case letter that follows a word boundary and makes it upper-case.
(For more information see the MDN doco for .replace().)
As far as doing it without using regular expressions, I'm not sure why you'd specifically want to avoid them, especially when the required expressions are pretty simple in this case (especially if you do the hyphen to space and first letter capitalisation in two steps as shown above). But there are endless ways to do this without regex using various combinations of JavaScript's string manipulation methods.
Do it like this
let someString = 'im a string';
console.log(someString.replace(/-/g, ' ')
.replace(/\w\S*/g, function (txt) {
return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
})
)
Output: Im A String
Short and great way:
const slugToText = (slug) => {
return slug.toLowerCase().replace(/-/g,' ')
}
Much Simplified answer
we can use String.prototype.replaceAll method to easily achieve this
function convertSlugToString(slug) {
return slug.replaceAll("-", " ");
}
incase you want to make sure the output is all lowercase then you can do the following
function convertSlugToString(slug) {
return slug.toLowerCase().replaceAll("-", " ");
}
Additional info:
String.prototype.replaceAll() is a ES2021 feature and it also has a great browser support with 93.64% global coverage, click here for more info
if you want to support IE then refer to the other answers