Ive been struggling with this a bit and haven't found anything good on the website. I'm trying to find the number of words in a textarea without split() (cuz it counts whitespaces and miscounts words in some situations) this is what i've tried :
text.addEventListener('input', () => {
let wordCounter = 0;
let sentenceCounter = 0;
let charCounter = text.value.split('').length;
let flag = false;
let flag2 = false;
if(text.value === ' ' || text.value === ''){
wordCounter = 0;
}
for(let z = 0; z < text.value.length; ++z){
if(text.value[z] == '.' && flag == false){
sentenceCounter++;
flag = true;
}
if((/\w/).test(text.value[z])){
flag = false;
}
}
for(let z = 0; z < text.value.length; ++z){
if(text.value[z] == " " && flag2 == false){
wordCounter++;
flag2 = true;
}
if((/\w/.test(text.value[z]))){
flag2 = false;
}
}
sentences.innerHTML = `${sentenceCounter} : Sentences`
char.innerHTML = `${charCounter} : Characters`
words.innerHTML = `${wordCounter} : Words`
});
the problem here is that it counts words only if press space so that means "fa" is not counted as a word but "fa " is. Thanks in advance for your help!
You need to increase the counter when you find a letter, instead of when you find a space. You can also count words and sentences on the same loop. To finish a word, had to change from comparing to " " to \W.
let sentenceCounter = 0, sentenceFinished = false,
wordCounter = 0, wordFinished = true,
input = "Test text. Test.";
for (let z = 0; z < input.length; ++z) {
var letter = input[z];
if (!sentenceFinished && letter == ".") {
sentenceCounter++;
sentenceFinished = true;
}
if (sentenceFinished && /\w/.test(letter)) {
sentenceFinished = false;
}
if (!wordFinished && /\W/.test(letter)) {
wordFinished = true;
}
if (wordFinished && /\w/.test(letter)) {
wordCounter++;
wordFinished = false;
}
}
console.log(`Words: ${wordCounter}, Sentences: ${sentenceCounter}`);
Related
I am trying to do a pop-up warning before the sales order is saved if the exact same item is entered twice when the order is created/modified on Netsuite. However, there is no window popping up and I am not sure what is wrong with the script. Here is what I got:
function validateitem (type){
var flag = true;
var numLine = nlapiGetLineItemCount('item');
itemArr = [];
if (type == 'item' && numLine > 0) {
for(var i = 0; i < numLine; i++) {
var itemSO = {};
itemSO.id = nlapiGetLineValue('item','item',i);
if (itemSO.id != null && itemSO.id !=''){
for (var j = 0; j < numLine; j++){
if(itenArr.indexOf(itemSO[i].id) === -1) {
itemArr.push(itemSO[i].id);}
else{
if (!confirm('You have entered a duplicate item for this sales order. Continue?'))
{
flag = false;
}
}
}
}
}
}
return flag;
}
Can somebody help, please?
Here is a slightly edited version:
function validateitem (){
var flag = true;
var numLine = nlapiGetLineItemCount('item');
itemArr = [];
if (numLine > 0) {
for(var i = 1; i <= numLine; i++) {
var itemSO = nlapiGetLineItemValue('item','item',i);
if (itemSO != null && itemSO !=''){
for (var j = 1; j <= numLine; j++){
if(itemArr.indexOf(itemSO[i]) === -1) {
itemArr.push(itemSO[i]);}
else{
flag = false;
}
}
}
}
}
if (flag == false){
alert('You have entered the same item twice.Continue?');
}
return flag;
}
This is the complete after-edit code that works:
function validateitem (){
var flag = true;
var numLine = nlapiGetLineItemCount('item');
itemArr = [];
if (numLine > 0) {
for(var i = 1; i <= numLine; i++) {
var itemSO = nlapiGetLineItemValue('item','item',i);
if (itemSO != null && itemSO !=''){
for (var j = i+1; j <= numLine; j++){
var itemSOplus = nlapiGetLineItemValue('item','item',j);
if(itemSO === itemSOplus) {
flag = false;
}
}
}
}
}
if (flag == false){
alert('You have entered the same item twice.Continue?');
}
return flag;
}
Thanks to Krypton!!
As per SuiteAnswers ID 10579, there are no paramters passed to the saveRecord client event. Therefore when your code checks the following:
if (type == 'item' && numLine > 0)
it finds that type equals undefined, so the condition is not met and the code will jump straight down to return flag which has been set to true.
Also note that in SuiteScript 1.0, line indexes start from 1 - not 0 as your code seems to assume.
EDIT - adding comment to form part of this answer:
I'd like to understand your logic behind itemSO[i] - as itemSO is not an array. Why not just compare the item from the current line of the inner loop with the current line of the outer loop and set the flag false if they match? Also, the inner loop need only start from j = i + 1 as the previous lines would have already been compared.
I am currently making a hangman game with javascript and I am struggling with how to remove and replace the previously selected word, with a new word. Currently I ahve my code set up so that when the player guesses the word correctly, a message pops up and asks the user if they want to play again. If they press Y, I call the function that randomly selects a word from and array and also uses the push method to fill and empty array with blank lines the same length of the chosen word. But when I call this function after Y has been pressed, the previous word doesnt go away and key presses also do not register.
var hangmanObject = {
randomWords: ['rock','paper','modular synthesizer', 'led zeppelin'],
chosenWord: "",
numWins: 0,
numLives: 10,
empty: [],
incorrect: [],
splitArray: []
}
function startFunction()
{
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
displayChosenWord();
}
function displayChosenWord()
{
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random()*hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
for (x = 0; x < hangmanObject.chosenWord.length; x++)
{
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push(" _ ");
}
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}
document.onkeyup = function(event)
{
var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
for (x = 0; x < hangmanObject.chosenWord.length; x++)
{
if (hangmanObject.chosenWord.charAt(x) === userGuess)
{
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}
}
if (hangmanObject.splitArray.indexOf(userGuess) === -1) //checking to see if wrong letter chosen
{
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect;
}
console.log(hangmanObject.empty);
if (hangmanObject.empty.indexOf(" _ ") === -1)
{
hangmanObject.numWins++;
// console.log("i won");
document.getElementById("wins").innerHTML = hangmanObject.numWins;
document.getElementById("Play").innerHTML = "Play Again? Y/N";
document.onkeyup = function(event)
{
// Determines which exact key was selected. Make it lowercase
var Choice = String.fromCharCode(event.keyCode).toLowerCase();
if (Choice === 'y')
{
hangmanObject.numLives = 10;
displayChosenWord();
}
}
}
if (hangmanObject.numLives <= 0)
{
document.getElementById("lose").innerHTML = "You Lose";
}
}
You are setting the document.onkeyup callback inside the callback, effectively disabling it for letter guesses.
Also, the empty array is never emptied so the next word is appended to the empty letters array from the previous word. Here's a simpler approach, by using a gameState flag, you can decide whether the user is entering letters to guess, or they are deciding to play again. Also, a single div for status can be used ;)
var hangmanObject = {
gameState: 'playing',
randomWords: [
'rock',
'paper',
'modular synthesizer',
'led zeppelin'
],
chosenWord: "",
numWins: 0,
numLives: 10,
empty: [],
incorrect: [],
splitArray: []
}
function startFunction() {
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
chooseNewWord();
}
function chooseNewWord() {
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random() * hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
// Reset guesses and misses
hangmanObject.empty = [];
hangmanObject.incorrect = [];
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push("_");
}
document.getElementById("blanks").innerHTML = hangmanObject.empty.join(" ");
}
document.onkeyup = function(event) {
var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
// Game status is "playing"
if (hangmanObject.gameState === 'playing') {
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === userGuess) {
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join(" ");
}
}
// checking to see if wrong letter chosen
if (hangmanObject.splitArray.indexOf(userGuess) === -1) {
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect.join(",");
}
// Some debug
console.log(hangmanObject.empty);
// WIN situation
if (hangmanObject.empty.indexOf("_") === -1) {
hangmanObject.numWins++;
// Set status message and game state
document.getElementById("status").innerHTML = "You won " + hangmanObject.numWins + " times";
hangmanObject.gameState = 'finished';
}
// LOSE situation
if (hangmanObject.numLives <= 0) {
// Set status message and game state
document.getElementById("status").innerHTML = "You Lose";
hangmanObject.gameState = 'finished';
}
// Set message if game finished
if (hangmanObject.gameState === 'finished') {
document.getElementById("Play").innerHTML = "Play Again? Y/N";
}
// Game status is "finished"
} else {
// If user selects play again
if (userGuess === 'y') {
// Set status back to "playing"
hangmanObject.gameState = 'playing';
// Reset lives and messages
hangmanObject.numLives = 10;
document.getElementById("status").innerHTML = "";
document.getElementById("LettersGuessed").innerHTML = "";
document.getElementById("Play").innerHTML = "";
// Choose new word
chooseNewWord();
} else {
// Set message
document.getElementById("status").innerHTML = "Goodbye!";
// Disable key handler
document.onkeyup = null;
}
}
}
startFunction();
<div id="numLives"></div>
<div id="blanks"></div>
<div id="LettersGuessed"></div>
<div id="status"></div>
<div id="Play"></div>
words joining - You need to clear the array.
no keyup - you replaced it with the 'y/n' keyup, you need to reset it.
also worth clearing the wrong letters and lives too on a new game.
see working example below:-
var hangmanObject = {
randomWords: ['rock', 'paper', 'modular synthesizer', 'led zeppelin'],
chosenWord: "",
numWins: 0,
numLives: 10,
empty: [],
incorrect: [],
splitArray: []
}
function startFunction() {
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
displayChosenWord();
}
function displayChosenWord() {
hangmanObject.empty = []; // empty the array
hangmanObject.incorrect = [];
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random() * hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push(" _ ");
}
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
document.getElementById("LettersGuessed").innerHTML = '';
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
document.onkeyup = gameKeyUp;
}
function gameKeyUp(event) {
var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === userGuess) {
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}
}
if (hangmanObject.splitArray.indexOf(userGuess) === -1) //checking to see if wrong letter chosen
{
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect;
}
console.log(hangmanObject.empty);
if (hangmanObject.empty.indexOf(" _ ") === -1) {
hangmanObject.numWins++;
// console.log("i won");
document.getElementById("wins").innerHTML = hangmanObject.numWins;
document.getElementById("Play").innerHTML = "Play Again? Y/N";
document.onkeyup = function(event) {
// Determines which exact key was selected. Make it lowercase
var Choice = String.fromCharCode(event.keyCode).toLowerCase();
if (Choice === 'y') {
hangmanObject.numLives = 10;
displayChosenWord();
}
}
}
if (hangmanObject.numLives <= 0) {
document.getElementById("lose").innerHTML = "You Lose";
}
}
displayChosenWord();
document.onkeyup = gameKeyUp;
<div id="numLives"></div>
<div id="blanks"></div>
<div id="LettersGuessed"></div>
<div id="wins"></div>
<div id="Play"></div>
<div id="lose"></div>
We get PDF's with the following formatted data.
14424, 14(100-103,706), 1488(zip 5-6,3),14(100-103,706,715,402-408,112),ect...
I need to take that data and parse it out to generate the given zip codes
14424,14100,14101,14102,14103,14706,14885,14886,14883
$('form').submit(function(e) {
$('textarea').val(parse_zip($('textarea').val()));
e.preventDefault();
});
function parse_zip(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
final_result = formated;
} else {
final_result = formated;
valid = false;
}
if (valid) {
return final_result;
} else {
return final_result + ' = Invalid';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw=="
crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha256-KXn5puMvxCw+dAYznun+drMdG1IFl3agK0p/pqT9KAo= sha512-2e8qq0ETcfWRI4HJBzQiA3UoyFk6tbNyG+qSaIBZLyW9Xf3sWZHN/lxe9fTh1U45DpPf07yj94KsUHHWe4Yk1A==" crossorigin="anonymous"></script>
<form>
<textarea class='form-control input-sm' rows="10">Before: 14424, 14(100-103,706), 1488(zip 5-6,3)</textarea>
<button type='submit'>
submit
</button>
</form>
<p class="help-block">
<br>Before: 14424, 14(100-103,706), 1488(zip 5-6,3)
<br>After: 14424,14100,14101,14102,14103,14706,14885,14886,14883
</p>
How can I parse this out?
EDIT
I have started on the parsing project, but I have come to a few stumbling blocks. here is what I have so far.
function rangeParser(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
var newString = '';
var openLeft = false;
for (var i = 0, len = formated.length; i < len; i++) {
if (formated[i] === '(') {
if (openLeft) {
/*if two left parentheses are open, then it's invalid*/
valid = false;
break;
} else {
openLeft = true;
}
} else if (formated[i] === ')') {
if (openLeft) {
openLeft = false;
} else {
/*if no left parentheses are open and you close it with a right parenthese, the it's invalid*/
valid = false;
break;
}
} else if (formated[i] === ',') {
if (openLeft) {
/*if you are between parentheses then use the '|' as a deliminator to be split latter*/
newString += '|';
} else {
newString += ',';
}
} else {
newString += formated[i];
}
}
if (valid) {
/*splits the string into seperate equations*/
var newArray = newString.split(',');
var append = '';
var substr = [];
var smsplit = [];
var addtome = [];
var addnext = '';
for (var i = 0, len = newArray.length; i < len; i++) {
if (/[^\d]/g.test(newArray[i])) {
if (/^\d/.test(newArray[i])) {
/*graps the appending digits*/
append = /^\d+/.exec(newArray[i])[0];
/*gets the string that will be parsed for generating automation*/
substr = newArray[i].substring(append.length).replace(/[^\d\-|,]+/g, '').split('|');
for (var j = 0, l = substr.length; j < l; j++) {
smsplit = substr[j].split('-');
if (smsplit.length === 2 && parseInt(smsplit[0]) < parseInt(smsplit[1])) {
if (parseInt(smsplit[0]) < parseInt(smsplit[1])) {
for (var k = parseInt(smsplit[0]), leng = parseInt(smsplit[1]); k < leng; k++) {
addnext = append + '' + k;
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
break;
}
}
} else {
/*if the ints are backwards, invalid*/
valid = false;
break;
}
} else if (smsplit.length === 1) {
addnext = append + '' + smsplit[0];
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
break;
}
} else {
/*if there are more than one dash, invalid*/
valid = false;
break;
}
if (!valid) {
break;
}
}
if (!valid) {
break;
}
} else {
/*if the string does not start with a digit, invalid*/
valid = false;
break;
}
} else if (newArray[i].length === 5) {
/*if it is a 5 digit number continue*/
addtome.push(newArray[i]);
continue;
} else {
/*if it has less or more than 5 digits and no special characters then it's invalid*/
valid = false;
break;
}
}
if (valid) {
final_result = uniq_fast(addtome).join(',');
}
}
} else {
valid = false;
}
if (valid) {
return final_result;
} else {
return formated + ' = Invalid';
}
}
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for (var i = 0; i < len; i++) {
var item = a[i];
if (seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out.sort();
}
This is a rudimentary answer and I would love to see if someone can come up with a better answer than mine, that out preforms it.
$('#sub').click(function() {
$('textarea').val(rangeParser($('textarea').val()));
});
$('#re').click(function() {
$('textarea').val('Before: 14424, 14(100-103,706), 1488(zip 5-6,3)');
});
function rangeParser(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
var invalidtext = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
var newString = '';
var openLeft = false;
for (var i = 0, len = formated.length; i < len; i++) {
if (formated[i] === '(') {
if (openLeft) {
/*if two left parentheses are open, then it's invalid*/
valid = false;
invalidtext = 'two left';
break;
} else {
openLeft = true;
newString += formated[i];
}
} else if (formated[i] === ')') {
if (openLeft) {
openLeft = false;
newString += formated[i];
} else {
/*if no left parentheses are open and you close it with a right parenthese, the it's invalid*/
valid = false;
invalidtext = 'no left';
break;
}
} else if (formated[i] === ',') {
if (openLeft) {
/*if you are between parentheses then use the '|' as a deliminator to be split latter*/
newString += '|';
} else {
newString += ',';
}
} else {
newString += formated[i];
}
}
if (valid) {
/*splits the string into seperate equations*/
var newArray = newString.split(',');
var append = '';
var substr = [];
var smsplit = [];
var addtome = [];
var addnext = '';
for (var i = 0, len = newArray.length; i < len; i++) {
if (/[^\d]/g.test(newArray[i])) {
if (/^\d/.test(newArray[i])) {
/*graps the appending digits*/
append = /^\d+/.exec(newArray[i])[0];
/*gets the string that will be parsed for generating automation*/
substr = newArray[i].substring(append.length).replace(/[^\d\-|,]+/g, '').split('|');
for (var j = 0, l = substr.length; j < l; j++) {
smsplit = substr[j].split('-');
if (smsplit.length === 2 && parseInt(smsplit[0]) < parseInt(smsplit[1])) {
if (parseInt(smsplit[0]) < parseInt(smsplit[1])) {
for (var k = parseInt(smsplit[0]), leng = parseInt(smsplit[1]); k <= leng; k++) {
addnext = append + '' + k;
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
invalidtext = 'ranged non five digit';
break;
}
}
} else {
/*if the ints are backwards, invalid*/
valid = false;
invalidtext = 'backwards range';
break;
}
} else if (smsplit.length === 1) {
addnext = append + '' + smsplit[0];
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
invalidtext = 'not five digit zip range';
break;
}
} else if (smsplit.length > 2) {
/*if there are more than one dash, invalid*/
valid = false;
invalidtext = 'more than one dash';
break;
}
if (!valid) {
break;
}
}
if (!valid) {
break;
}
} else {
/*if the string does not start with a digit, invalid*/
valid = false;
invalidtext = 'donst start with digit';
break;
}
} else if (newArray[i].length === 5) {
/*if it is a 5 digit number continue*/
addtome.push(newArray[i]);
continue;
} else {
/*if it has less or more than 5 digits and no special characters then it's invalid*/
valid = false;
invalidtext = 'non range not five digit';
break;
}
}
if (valid) {
final_result = uniq_fast(addtome).join(',');
}
}
} else {
/*if starting string doesn't have digit at first*/
invalidtext = 'begin non digit';
valid = false;
}
if (valid) {
return final_result;
} else {
return formated + ' = Invalid ' + invalidtext;
}
}
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for (var i = 0; i < len; i++) {
var item = a[i];
if (seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out.sort();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<textarea class='form-control input-sm' rows="10">Before: 14424, 14(100-103,706), 1488(zip 5-6,3)</textarea>
<button id="sub">
submit
</button>
<button id="re">
Reset
</button>
<p class="help-block">
<br>Before: 14424, 14(100-103,706), 1488(zip 5-6,3)
<br>After: 14100,14101,14102,14103,14424,14706,14883,14885,14886
</p>
Here is the javascript code:
I need help getting the word to display after the player looses.
var can_play = true;
//this is the array of words
var words = new Array("VALIDATE", "DESIGN", "INPUT", "ARRAY", "OBJECT", "DOCUMENTATION", "JQUERY", "CALCULATE", "ABSOLUTE", "DREAMWEAVER", "BROWSER", "HTML", "CONCATINATION");
var display_word = "";
var used_letters = "";
var wrong_guesses = 0;
//this will allow the letters to be entered in only 1 time
function selectLetter(l) {
if (can_play == false) {
return;
}
if (used_letters.indexOf(l) != -1) {
return;
}
used_letters += l;
document.game.usedLetters.value = used_letters;
if (to_guess.indexOf(l) != -1) {
// this will display the correct letter guesses
pos = 0;
temp_mask = display_word;
while (to_guess.indexOf(l, pos) != -1) {
pos = to_guess.indexOf(l, pos);
end = pos + 1;
start_text = temp_mask.substring(0, pos);
end_text = temp_mask.substring(end, temp_mask.length);
temp_mask = start_text + l + end_text;
pos = end;
}
display_word = temp_mask;
document.game.displayWord.value = display_word;
if (display_word.indexOf("*") == -1) {
// this will display a message if you win
$('#win').html("Well done, you won!");
can_play = false;
}
} else {
// this will display the incorrect letter guesses
wrong_guesses += 1;
$('#wrong_guesses').html(wrong_guesses);
if (wrong_guesses == 6) {
// this will display a message if you loose
$('#win').html("Sorry, you have lost!");
can_play = false;
}
}
}
//this will reset the game to play again
function reset() {
selectWord();
document.game.usedLetters.value = "";
guessed_letters = "";
wrong_guesses = 0;
$('#win').html("");
$('#wrong_guesses').html("");
}
//this will have the computer select a word from my array
function selectWord() {
can_play = true;
random_number = Math.round(Math.random() * (words.length - 1));
to_guess = words[random_number];
// this will display mask
masked_word = createMask(to_guess);
document.game.displayWord.value = masked_word;
display_word = masked_word;
}
function createMask(m) {
mask = "";
word_length = m.length;
for (i = 0; i < word_length; i++) {
mask += "*";
}
return mask;
}
$('#win').html("Sorry, you have lost, the word was " + to_guess + "!");
You assigned the to be guessed word here:
to_guess = words[random_number];
You would learn much from posting your code to Code Review.
I am trying to get it so that if I type in a name that ends with a space, the textfield will go red. Most of the code works its just one method does not seem to be working.
The issue must be somewhere in the last index part?
var NamePass = true;
function ValidateName() {
var BlankPass = true;
var GreaterThan6Pass = true;
var FirstBlankPass = true;
var BlankMiddleName = true;
if (document.getElementById('Name').value == "") {
BlankPass = false;
}
var Size = document.getElementById('Name').value.length;
console.log("Size = " + Size);
if (Size < 7) {
GreaterThan6Pass = false;
}
if (document.getElementById('Name').value.substring(0, 1) == " ") {
FirstBlankPass = false;
}
var LastIndex = document.getElementById('Name').value.lastIndexOf();
if (document.getElementById('Name').value.substring((LastIndex - 1), 1) == " ") {
FirstBlankPass = false;
}
string = document.getElementById('Name').value;
chars = string.split(' ');
if (chars.length > 1) {} else
BlankMiddleName = false;
if (BlankPass == false || GreaterThan6Pass == false || FirstBlankPass == false || BlankMiddleName == false) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
http://jsfiddle.net/UTtxA/10/
lastIndexOf gets the last index of a character, not the last index in a string. I think you meant to use length instead:
var lastIndex = document.getElementById('Name').value.length;
Another problem with that, though, is that substring takes a start and end index, not a start index and a substring length. You could use substr instead, but charAt is easier:
if (document.getElementById('Name').value.charAt(lastIndex - 1) == " ") {
FirstBlankPass = false;
}
Now, for some general code improvement. Instead of starting with all your variables at true and conditionally setting them to false, just set them to the condition:
var NamePass = true;
function ValidateName() {
var value = document.getElementById('Name').value;
var BlankPass = value == "";
var GreaterThan6Pass = value.length > 6;
var FirstBlankPass = value.charAt(0) == " ";
var LastBlankPass = value.charAt(value.length - 1) == " ";
var BlankMiddleName = value.split(" ").length <= 1;
if (BlankPass || GreaterThan6Pass || FirstBlankPass || LastBlankPass || BlankMiddleName) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
A couple more points of note:
It’s probably a good idea to use camelCase variable names instead of PascalCase ones, the latter usually being reserved for constructors
blah == false should really be written as !blah
An empty if followed by an else can also be replaced with if (!someCondition)
That function looks like it should return true or false, not set the global variable NamePass
Penultimately, you can sum this all up in one regular expression, but if you intend to provide more specific error messages to the user based on what’s actually wrong, then I wouldn’t do that.
function validateName() {
return /^(?=.{6})(\S+(\s|$)){2,}$/.test(document.getElementById('name').value);
}
And finally — please keep in mind that not everyone has a middle name, or even a name longer than 6 characters, as #poke points out.