javascript validation - first capital only - how to? - javascript

// Validate Sentence Case
if(dataEntryCaseId.toString().match("4")){
var newValue = toTitleCase(value);
if(newValue != value){
for(var x = 1, j = value.length; x < j; x++){
if(value.charAt(x) != newValue.charAt(x)){
valid = false;
$("#text_10").attr({"value":$("#text_10").attr("value").replace(value.charAt(x), "")});
finalVal = finalVal.replace(value.charAt(x), "");
}
}
}
}
if(!valid){
for(var x = 0, j = styleNoteJsonData.styleGroupNote.length; x < j; x++){
if(styleNoteJsonData.styleGroupNote[x].styleName == styleGroupName){
alert(styleNoteJsonData.styleGroupNote[x].styleNote);
$(".styleNote").addClass("alertRed");
SendErrorMessage(styleNoteJsonData.styleGroupNote[x].styleNote);
}
}
} else {
$(".styleNote").removeClass("alertRed");
}
if(finalVal.length > 0){
return true;
}
return valid;
}
function toTitleCase(str){
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}).replace(/\s/, '');
}
I need to rework this to only allow the first letter to be capitalized (it doesn't have to be)
I was trying to do this with regex - which i'm not sure is needed if the javascript validation was correct - seefunction toTitleCase(str)
regex seems overkill - but maybe because the current validation is using it, it might be easier to incorporate, but I wanted to see if their were other options within the parameters of the current code.

Your question is not very clear. If you want to only keep the first uppercase, use this function:
function toTitleCase(str){
return str.charAt(0)+str.substring(1).toLowerCase();
}
Additional notes:
Add str = str.replace(/\s/g,""); before return ... when you want to remove all white-space characters.
If you only want to remove the beginning and ending whitespace characters, add str = str.replace(/^\s+/,"").replace(/\s+$/,""); instead,

Related

Protecting Punctuation in Custom Uppercase-Conversion Function in JavaScript

function func1(word) {
matches = word.match(/([A-Z][a-z]+[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]*)/g);
if (!matches || matches.length === 1) {
return word.toUpperCase(); }
else return func2(matches) }
function func2(matched) {
x = (matches.length) - 1;
matches[x] = matches[x].toUpperCase();
return matches.join('');
}
function func3(isolated) {
output = isolated.split(/\s/);
output2 = [];
for (i = 0; i < output.length; i++) {
output2.push(func1(output[i])); }
output = output2.join(' ');
return output;
}
The idea is to convert things to uppercase, rendering McGee, McIntosh, etc as McGEE, McINTOSH, etc. Resulted from this thread here: JavaScript Convert Names to Uppercase, Except Mc/Mac/etc
Initially it was destroying all punctuation, because it didn't fit in with the matches so it just vanished into thin air. So I added the punctuation into the regular expression on line two.
Unfortunately, I then came across the word "Free-Throw", which renders as "Free-THROW" instead of "FREE-THROW". Under the old code it rendered as "FreeTHROW", which isn't any better.
Is there a way I can tackle this other than carefully-phrased inputs? It's for an After Effects expression so there aren't any users to deal with but I'd rather be able to include that hyphen, and if a double-barreled McSomething shows up (McGee-Smith for example) I won't have much choice.
The comment suggesting limited scope is correct, just the wrong way around: rather than defining which prefixes to handle I can easily define punctuation to protect. Dashes and apostrophes are the only characters I really have to worry about appearing mid-word, and dashes are always going to be between "words" within a word.
So instead of all-capsing the last match to the regular expression, I now all-caps both that and any match which ends in a dash.
Apostrophes are removed before the process stars, and re-inserted at the same index after capitalisation is complete.
function func1(word) {
filter = word.indexOf("’");
word = word.replace("’","");
matches = word.match(/([-!$%^&*()_+|~=`{}\[\]:"“”;'’<>?,.\/]*[A-Z][a-z]+[-!$%^&*()_+|~=`{}\[\]:"“”;'’<>?,.\/]*)/g);
if (!matches || matches.length === 1) {
func2out = word.toUpperCase();
if (filter >= 0){
func2out = [func2out.slice(0,filter), "’", func2out.slice(filter)].join('');
}
return func2out;}
else return func2(matches) }
function func2(matched) {
for(x = 0; x < matches.length; x++) {
if (matches[x].indexOf('-') >= 0 || (x == (matches.length-1))) matches[x] = matches[x].toUpperCase(); }
func2out = matches.join('');
if (filter >= 0) {
func2out = [func2out.slice(0,filter), "’", func2out.slice(filter)].join('');
}
return func2out;
}
function func3(isolated) {
output = isolated.split(/\s/);
output2 = [];
for (i = 0; i < output.length; i++) {
output2.push(func1(output[i])); }
output = output2.join(' ');
return output;
}

Javascript Palindrome Check

I have to write a script to check if a word entered by a user is a Palindrome. I've gotten as far as validating the word and displaying the number of characters. Also not supposed to use the reverse method.
I've looked at some of the examples here and think I need to turn the user input into a string and use a "for" loop and if/else statement. But how do I turn the user input into a string in order to check each character? This is a total mess but it's all I've got so far:
function checkWord(userWord3) {
var answer = "Your word is";
answer += retrieveWord(userWord3);
return (answer);
}
function retrieveWord(userWord) {
var string = userWord;
var i = userWord.length;
for(var i = 0; i < str.length / 2; i++) {
alert(str[i], str[str.length -i -1]);
if( str[i] != str[str.length - i -1] ) {
return false;
}
}
}
You can try this function
function isPalindrome(str){
if(str.length < 2) return true;
if(str[0] != str.slice(-1)) return false;
return isPalindrome(str.slice(1,-1));
}
It uses recursion and its logic is as follows
The empty and 1 character string are considered palindromes
if(str.length == 0 || str.length == 1) return true;
if the first and last characters are not the same the word is not a palindrome
if(str[0] != str.slice(-1)) return false;
if the first and last are the same continue searching in the remaining string
return isPalindrome(str.slice(1,-1));
var result = document.querySelector(".result");
var palindrome = "<span class='palindrome'>it is a palindrome</span>";
var notpalindrome = "<span class='notpalindrome'>it is NOT a palindrome</span>";
function isPalindrome(str){
if(str.length == 0 || str.length == 1) return true;
if(str[0] != str.slice(-1)) return false;
return isPalindrome(str.slice(1,-1));
}
document.querySelector("input").addEventListener("keyup", function(){
if(isPalindrome(this.value)){
result.innerHTML = palindrome;
} else {
result.innerHTML = notpalindrome;
}
})
.palindrome{color: green;}
.notpalindrome{color: red;}
<input type="text" />
<span class="result"></span>
How are you collecting the user input? In just about every case, it will come into the program as a string (i.e. textbox, prompt), so you don't have to worry about converting it into one.
This code simply takes the word, breaks it into an array, reverses the array and then compares that reversal against the original word. It works for me:
function test(input){
var originalData = input;
var a = [];
for(var i = 0; i < input.length; ++i){
a.push(input.charAt(i));
}
a.reverse();
return (a.join('') === originalData) ? true : false;
}
var word = document.getElementById("userWord");
alert(test(word));
See working version at: https://jsfiddle.net/6cett0bc/6/
The most basic version I can think of is to split the word into letters and check the first against the last, until you end up in the middle, where it doesn't matter if there is an odd amount of letters.
UPDATE I've tested the performance of various implementations and changed my array based answer to a pure string based solution.
If you're curious, here are the performance benchmarks
The fastest solution (so far):
function palindrome(word) {
var middle = Math.ceil(word.length / 2), // determine the middle
i; // prepare the iteration variable
// loop from 0 to middle
for (i = 0; i <= middle; ++i) {
// check letter i against it counterpart on the opposite side
// of the word
if (word[i] !== word[(word.length - 1) - i]) {
// it is not a palindrom
return false;
}
}
// otherwise it is
return true;
}
// listen for clicks on the button and send the entered value to the palindrom function
document.querySelector('button').addEventListener('click', function(e) {
// obtain the input element
var element = document.querySelector('input');
// add/remove the 'palindrom' CSS class to the input field, depending on
// the output of palindrome function
if (palindrome(element.value)) {
element.classList.add('palindrome');
}
else {
element.classList.remove('palindrome');
}
});
input {
color: red;
}
input.palindrome {
color: green;
}
<input name=check placeholder=palindrome><button>check</button>
The text turns green if you have entered a palindrome successfully, red (default) otherwise.

How to apply special characters in string?

Suppose we have the following string object:
var str = "Real\bWorl\bd";
considering \b as BackSpace character, I want a mechanism to get
ReaWord
as result, this means BackSpace character some how compiled within the string.
aside from BackSpace, this special character might be Delete.
Thanks in advance....
try this
function replaceBackslash(str)
{
return str.split(/[a-z]\b/).join("")+ str.charAt(str.length -1);
}
replaceBackslash( "Real\bWorld\bddd" );
replaceBackslash( "Real\bWorld" );
function formatStr(str){
if(str.indexOf("\b")!=-1){
return formatStr(str.substring(0, str.indexOf("\b")-1) +
str.substring(str.indexOf("\b")+1, str.length));
}
else return str;
}
var str = "Real\bWor\bld";
alert(formatStr(str));
Check this
function removeBackspaces()
{
var str = "Real\bWorl\bd";
var word = "";
for(var i=0; i < str.length; i++)
{
if(str[i] != '\b')
{
word += str[i]
}
else
{
//var lastIndex = word.lastIndexOf(" ");
word = word.substring(0, word.length-1);
}
}
return word;
}
use following code
unescape(str)

error in cloned substring() function in js

I am trying to make a function in js that checks whether a substring exists in main string. For eg:- main = 111010 and substring = 011 should return false as substring does not exists in main string but my code returns true. Here is the code below.
var string = "111010",
substr = "011";
var found=false;
outter:for(var i=0;i<string.length;i++){
if(string.charAt(i)==substr.charAt(0)){
var k=i+1;
inner:for(j=1;j<substr.length;j++){
if(string.charAt(k++)==substr.charAt(j)){
found=true;
continue inner;
}else{
continue outter;
}
}
}
}
if(found!=false){
console.log("y")
}else{
console.log("n");
}
You forget to re-initialize the found variable.
var string = "111010",
substr = "0110";
var found=false;
for(var i=0;i<string.length;i++){
if(string.charAt(i)==substr.charAt(0)){
var k=i+1;
for(j=1; j < substr.length;j ++)
if(string.charAt(k++)==substr.charAt(j)){
found=true;
}else{
found = false; // <<--this
break;
}
if(found) break;
}
}
if(found!=false){
console.log("y")
}else{
console.log("n");
}
Your code always returns true if it ever find a single common letter between your string and substring.
And please, DO NOT USE LABELS, they are simply bad. Thanks!
Demo: http://jsfiddle.net/fer52ufd/
Here is how your code should actually be.
var found = false;
for (var i = 0; i < string.length; i++) { // starting position
found = true; // All letters match, prove the opposite
for (j = 0; j < substr.length; j++) { // Compare the given string with the string starting at i
if (string.charAt(i + j) != substr.charAt(j)) { // If one letter does not match, stop searching
found = false;
break;
}
}
if (found) break;
}
Why treat the first letter separately?
Don't use labels
Don't search for the match, search for letters that do not match and, if you find none, the strings match.
Do not use unnecessary index variables (as k), the position of the letter on the needle string is j and in the hay string is i+j
This is the code to check that:
var string = "111010", substr = "011";
var test = string.indexOf(substr);
if (test >= 0) {
alert('yes');
} else {
alert('no');
}

Test if input values match constant value

Ive got an assignment and am a bit stuck.
Need to match an input string to the values in a constant, but I am matching individual characters.
My constant would be ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUWXYZ'
My input would be, var input = 'ABOZ'
I need a test to check if each letter in the input variable exist in the ALPHABET constant.
Hope I made sense.
Cheers
Here's a single line answer to your question:
(ALPHABET.match(new RegExp((input.split('').join('|')), 'g'))).length == input.length
which would return true only if all the characters in input are present in ALPHABET
Here's a working demo http://jsfiddle.net/kayen/akL4A/
One way is to loop over the input and search if it exits in the constant
Possible code
var ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUWXYZ';
var input = 'ABOZ'
var count = 0;
for(x in input) {
if(ALPHABET.indexOf(input[x])>-1){
count++;
continue;
}
else{
break;
}
}
if(count==input.length) {
alert("true");
}
Demo
Tested and works in Firefox 16. Remember this implementation does not verify if input is null or other defensive checks. You should do it by yourself.
This is a case sensitive result.
Case insensitive :
function validInput(input) {
var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
for (var i = 0; i < input.length; i++) {
var charAtI = input.charAt(i);
var indexOfCharAtI = ALPHABET.indexOf(charAtI);
if (indexOfCharAtI < 0) {
return false;
}
}
return true;
}
Case insensitive :
function validInput(input) {
var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
for (var i = 0; i < input.length; i++) {
var charAtI = input.charAt(i);
charAtI = charAtI.toUpperCase();
var indexOfCharAtI = ALPHABET.indexOf(charAtI);
if (indexOfCharAtI < 0) {
return false;
}
}
return true;
}
Here's an example of a function which would return true for a match or false for a mismatch. (Please note this is a case sensitive test).
var ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var input = 'ABOZ';
function testStr(str, constant){
var matchFlag = true;
var strSplit = str.split("");
for(var i=0; i<strSplit.length;i++){
if(constant.indexOf(strSplit[i]) == -1){
matchFlag = false;
}
}
return matchFlag;
}
alert(testStr(input, ALPHABET)); //TRUE
DEMO

Categories

Resources