Checking if a new line exist using regex - javascript

I am writing a javascript to add {y} at the start and {/y) at the end to non english characters. I also need it to leave empty lines as it is. But in the current scenario, it is adding {y}{/y) to empty lines/new lines.
var lyrics = document.getElementById('userInput');
function printSong() {
var input = lyrics.value;
var lines = input.split('\n');
var generatedText = "";
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(/[A-z]|[0-9]{2}/) != null | lines[i].match(/\s/) != null) {
generatedText = generatedText + lines[i] + '\n';
} else {
generatedText = generatedText + "{y}" + lines[i] + "{/y}" + '\n';
}
}
document.getElementById('output').value = generatedText;
}
<div class="container-fluid">
<div class="col-xs-12">
<div class="col-xs-5">
<textarea id="userInput" class="form-control" cols="40" rows="10" placeholder="Enter song lyrics here">testing
அஇஉ்உ்உ</textarea>
</div>
<div class="col-xs-2" style="text-align: center">
<button type="button" class="btn btn-success" onclick="printSong()">Generate tags</button>
</div>
<div class="col-xs-5">
<textarea disabled id="output" class="form-control" cols="40" rows="10" placeholder="Generated Song"></textarea>
</div>
</div>
</div>

Avoiding adding your markers to blank lines is simply a matter of adding
!lines[i].trim() ||
...to the beginning of your if. That takes the line, strips any leading and trailing whitespace from it, and sees if the result is empty. ("" is a falsy value, so !"" is true.) If it is blank, it skips the regex check (because || short-circuits if the left-hand operand is truthy) and we go into the if block (so we don't add markers to blank lines).
But as Wiktor pointed out:
For the logical OR operation, it's ||, not |
[A-z] matches all characters between upper case A and lower case z. There are many characters after Z and before a that will also be matched.
Also: [A-z]|[0-9]{2} means "a single character A through z or two digits." If that's what you really meant, fine, but if you meant "two characters which are either A through z or 0 through 9" you'd combine them into a single character class. I haven't done that below, on the theory you may want the condition the way it is.
And finally: If all you want to do is check if a string matches an expression, you don't want match; instead, use test on the expression. E.g.
if (string.match(expression) != null)
becomes
if (expression.test())
That lets the regular expression engine stop as soon as it knows the result and not bother to build the result array.
With those changes:
var lyrics = document.getElementById('userInput');
function printSong() {
var input = lyrics.value;
var lines = input.split('\n');
var generatedText = "";
for (var i = 0; i < lines.length; i++) {
if (!lines[i].trim() || /[a-zA-Z]|[0-9]{2}/.test(lines[i]) || lines[i].match(/\s/) != null) {
generatedText = generatedText + lines[i] + '\n';
} else {
generatedText = generatedText + "{y}" + lines[i] + "{/y}" + '\n';
}
}
document.getElementById('output').value = generatedText;
}
<div class="container-fluid">
<div class="col-xs-12">
<div class="col-xs-5">
<textarea id="userInput" class="form-control" cols="40" rows="10" placeholder="Enter song lyrics here">testing
அஇஉ்உ்உ</textarea>
</div>
<div class="col-xs-2" style="text-align: center">
<button type="button" class="btn btn-success" onclick="printSong()">Generate tags</button>
</div>
<div class="col-xs-5">
<textarea disabled id="output" class="form-control" cols="40" rows="10" placeholder="Generated Song"></textarea>
</div>
</div>
</div>

Related

How can I prevent my program from converting selected number which starts with 0 to octal value using javascript?

When I select a number that starts with 0, such a number is converted to its octal form which I don't want but works perfectly well for those that didn't start with 0. Attached is pictures explaining what I mean.
Before Selection of Number starting with 0
After Selection of Number starting with 0
From the picture you can see 0703 got converted to 451. How can I stop this.
let phoneNumberSelector = document.querySelector("#phone");
const mtnNumber = ['703', '706', '803', '806', '810', '813', '814', '816', '903', '906', '913', '0703', '0706'];
phoneNumberSelector.addEventListener('keyup', (e) => {
removeElements();
for (let i of mtnNumber) {
// i = i.toString();
if (i.startsWith(phoneNumberSelector.value) && phoneNumberSelector.value != '') {
let listItem = document.createElement("li");
listItem.classList.add('list-items');
listItem.style.cursor = 'pointer';
listItem.setAttribute('onclick', "displayNames(" + i + ")")
let word = "<b>" + i.slice(0, phoneNumberSelector.value.length) + "</b>";
word += i.slice(phoneNumberSelector.value.length);
listItem.innerHTML = word;
document.querySelector('.list').appendChild(listItem);
}
}
})
function displayNames(param) {
phoneNumberSelector.value = param;
removeElements();
}
function removeElements() {
let items = document.querySelectorAll('.list-items')
items.forEach((element) => {
element.remove();
});
}
<section class="section1"></section>
<section class="section2">
<div class="reg-form">
<form action="" method="">
<div class="form-container">
<h1 style="text-align: center;">Phonie</h1>
<div class="input-reg email-input">
<label for="username">Username</label>
<input id="username" type="text" name="username">
</div>
<div class="list-div">
<ul class="list"></ul>
</div>
<div class="input-reg email-input">
<label for="phone">Phone Number</label>
<input id="phone" type="text" name="phone">
</div>
<div class="input-reg email-input">
<input class="submit-btn submit-btn2" type="submit" value="Check Number">
</div>
</div>
</form>
</div>
</section>
The numbers are getting converted to octal because you are passing the number (of type string) to the displayNames function as a number (without quotes).
This is the offending line:
listItem.setAttribute('onclick', "displayNames(" + i + ")")
with the value of i set to "0703", the value for onclick becomes "displayNames(0703)".
You can fix this by adding quotes around the i variable in the string passed as onclick.
For example:
listItem.setAttribute('onclick', "displayNames('" + i + "')");
or with a string template to make it a bit easier to read:
listItem.setAttribute('onclick', `displayNames("${i}")`);

Making Caser Cipher Case sensitive in JavaScript?

<body>
<div class="container">
<div class="row">
<h1 class="mx-auto">Secured Data Cypher</h1>
</div>
<div class="row">
<h5 class="mx-auto desc"><br><br>Enter Your Desired Message which you want Encrypted <br><br> For example: ****_***123 </h5>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<h4>Plain Text</h4>
<textarea class="form-control" id="plain-text" rows="7"></textarea>
</div>
<div class="input-group mb-3">
<input type="number" min="0" max="25" class="form-control" id="my-key" placeholder="Key (Digits Only)">
<div class="input-group-append">
<button class="btn btn-outline-success" type="button" onclick="encrypt()">Encrypt</button>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Cipher Text</h4>
<textarea readonly class="form-control" id="cipher-text" rows="7"></textarea>
</div>
<button type="button" class="btn btn-outline-danger" onclick="decrypt()">Decrypt</button>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Original Text</h4>
<textarea readonly class="form-control" id="original-text" rows="7"></textarea>
</div>
</div>
</div>
</div>
</body>
<!- JS for Cypher Starts here ->
<script>
function encrypt() {
// Empty Original Text
document.getElementById("original-text").value = "";
var k = document.getElementById("my-key").value;
var p = document.getElementById("plain-text").value;
if (!(k >= 0 && k < 26)) {
alert("Key should be between 0 and 25");
return;
}
if (p.length === 0) {
alert("Plain Text is empty");
}
p = p.toLowerCase();
var cipher = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < p.length; i++) {
var current = p.charAt(i);
if (!isLetter(current)) {
cipher += current;
continue;
}
var index = 0;
index = alphabet.indexOf(current);
var shifted = (parseInt(index) + parseInt(k)) % 26;
cipher += alphabet.charAt(shifted);
}
document.getElementById("cipher-text").value = cipher;
}
function decrypt() {
var k = document.getElementById("my-key").value;
var cipher = document.getElementById("cipher-text").value;
if (!(k >= 0 && k < 26)) {
alert("Key should be between 0 and 25");
return;
}
var original = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < cipher.length; i++) {
var current = cipher.charAt(i);
if (!isLetter(current)) {
original += current;
continue;
}
var index = 0;
index = alphabet.indexOf(current);
var num = parseInt(index) - parseInt(k);
var shifted = (num + 26) % 26;
original += alphabet.charAt(shifted);
}
document.getElementById("original-text").value = original;
}
function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i);
}
</script>
<!- JS for Cypher Ends here ->
This code above only encrypts texts in lowercase
For example:
Result: Leo_123 -(with shift number of 2)-> ngq_123 -(after decryption)-> leo_123
but my expected result is:
Leo_123 -(with shift number of 2)-> Ngq_123 -(after decryption)-> Leo_123
the first part of the code is from my body tag and I am using bootstrap to make this happen
The javascript code follows the main principal but I want to modify it to get the expected results.
Make these changes:
Make alphabet a global variable that is initialised only once, and includes also the capital letters
Define a SIZE variable that is the length of this alphabet, and use that variable instead of the hard-coded 26, where ever you had used it.
Remove the statement that makes p lowercased.
Here is the adapted code:
// Make this global and add CAPITALS
var alphabet = "abcdefghijklmnopqrstuvwxyz";
alphabet += alphabet.toUpperCase();
var SIZE = alphabet.length; // Use this instead of 26
function encrypt() {
// Empty Original Text
document.getElementById("original-text").value = "";
var k = +document.getElementById("my-key").value;
var p = document.getElementById("plain-text").value;
if (!(k >= 0 && k < SIZE)) {
alert("Key should be between 0 and " + (SIZE-1));
return;
}
if (p.length === 0) {
alert("Plain Text is empty");
}
// Don't lowercase!
// p = p.toLowerCase();
var cipher = "";
for (var i = 0; i < p.length; i++) {
var current = p.charAt(i);
if (!isLetter(current)) {
cipher += current;
continue;
}
var index = alphabet.indexOf(current);
var shifted = (index + k) % SIZE;
cipher += alphabet.charAt(shifted);
}
document.getElementById("cipher-text").value = cipher;
}
function decrypt() {
var k = +document.getElementById("my-key").value;
var cipher = document.getElementById("cipher-text").value;
if (!(k >= 0 && k < SIZE)) {
alert("Key should be between 0 and " + (SIZE-1));
return;
}
var original = "";
for (var i = 0; i < cipher.length; i++) {
var current = cipher.charAt(i);
if (!isLetter(current)) {
original += current;
continue;
}
var index = alphabet.indexOf(current);
var num = index - k;
var shifted = (num + SIZE) % SIZE;
original += alphabet.charAt(shifted);
}
document.getElementById("original-text").value = original;
}
function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i);
}
<div class="container">
<div class="row">
<h1 class="mx-auto">Secured Data Cypher</h1>
</div>
<div class="row">
<h5 class="mx-auto desc"><br><br>Enter Your Desired Message which you want Encrypted <br><br> For example: ****_***123 </h5>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<h4>Plain Text</h4>
<textarea class="form-control" id="plain-text" rows="7"></textarea>
</div>
<div class="input-group mb-3">
<input type="number" min="0" max="51" class="form-control" id="my-key" placeholder="Key (Digits Only)">
<div class="input-group-append">
<button class="btn btn-outline-success" type="button" onclick="encrypt()">Encrypt</button>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Cipher Text</h4>
<textarea readonly class="form-control" id="cipher-text" rows="7"></textarea>
</div>
<button type="button" class="btn btn-outline-danger" onclick="decrypt()">Decrypt</button>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Original Text</h4>
<textarea readonly class="form-control" id="original-text" rows="7"></textarea>
</div>
</div>
</div>
</div>

My form Verification and Validation with JS is not working

I want to verify and validate a form in HTML, and insert messages in Front if necessary ("eg.Pseudo/Username not long enough"), which will serve as a "new user" form for a website.
I want to start by understanding my mistake for the "Pseudo" verification and validation.
I currently have the following in HTML:
<form id="formNouveau" onsubmit="return valideForm2()">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
and the following in JS (focusing on the pseudo validation):
function valideForm(){
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
function valPseudo(text)
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of text.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert ("Please write a pseudo");
if (letterCount + numberCount > 40)
alert ("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert ("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert ("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert ("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
}
What do you think?
Thank you!
You have a mix of variable names in the function and a sub function with incorrect syntax. You're not preventing the form from submitting. Fixed both and it works:
function valideForm(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of valPseudo.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert("Please write a pseudo");
if (letterCount + numberCount > 40)
alert("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
document.getElementsByTagName('form')[0].addEventListener('submit', valideForm);
<form id="formNouveau">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
function valideForm2(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
console.log(valPseudo);
function validate(text) {
let letters = "abcdefghijklmnopqrstuvwxyz";
let numbers = "0123456789";
let letterCount = 0;
let numberCount = 0;
for (let character of text.toLowerCase()) {
if (letters.includes(character)) ++letterCount;
else if (numbers.includes(character)) ++numberCount;
else return false; //A non [a-zA-Z0-9] character was present
}
if (text == "") alert("Please write a pseudo");
if (letterCount + numberCount > 40) alert("Pseudo is too long"); //The name is too long
if (letterCount + numberCount < 5) alert("Pseudo is too short"); //The name is too short
if (letterCount < 1) alert("one letter needed at least"); //There aren't enough [a-zA-Z] characters
if (numberCount < 1) alert("one number needed at least"); //There aren't enough [0-9] characters
return 0; //Everything is okay!
}
validate(valPseudo);
}
const form = document.getElementById("formNouveau");
form.addEventListener("submit", valideForm2);
Try this JS code instead, it has the same functionality but has some modifications, the main problem was regarded to e.preventDefault() which forces page not to reload. Moreover you had some little bugs. For more information on preventDefault you can visit link: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
You're better off testing the input against a REGEX expression rather than testing for each failure case...
There a numerous REGEX testers and cheat-sheets online for what you're trying to do.

How to change text color if one var is greater than or equal to another var?

I'm writing a small script to change the color of some span text based on the value of available characters left when typing in a text box.
I have the counter working which shows the number of characters left, but I can't seem to get the color to change when the number of characters left is greater than or equal to the number of max characters allowed.
Here's my javascript code:
$(document).ready(function(){
var maxChar = 300;
$("textarea").keyup(function() {
var length = $(this).val().length;
var charCount = maxChar - length;
$("#charCount").text(charCount);
if (charCount >= maxChar) {
document.getElementById("charCount").style.color = "#ff3343";
}
})
});
HTML for text box:
<div class="form-group col-12">
<label for="hostDesc">Description</label>
<textarea class="form-control" name="hostDesc" id="hostDesc" min="0" maxlength="300" data-ng-model="hostDesc" aria-describedby="descHelp" placeholder="Leave a description" rows="8" style="height: 150px" required></textarea>
<p class="text-small text-muted mb-0"><span id="charCount">300</span> characters remaining</p>
</div>
You had the >= the wrong way:
$(document).ready(function() {
var maxChar = 300;
$("textarea").keyup(function() {
var length = $(this).val().length;
var charCount = maxChar - length;
$("#charCount").text(charCount);
if (charCount <= maxChar) {
document.getElementById("charCount").style.color = "#ff3343";
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-12">
<label for="hostDesc">Description</label>
<textarea class="form-control" name="hostDesc" id="hostDesc" min="0" maxlength="300" data-ng-model="hostDesc" aria-describedby="descHelp" placeholder="Leave a description" rows="8" style="height: 150px" required></textarea>
<p class="text-small text-muted mb-0"><span id="charCount">300</span> characters remaining</p>
</div>
Hope this helps,

How do I make separate characters in a string random fonts?

I'm currently trying to write a block of Javascript in my webpage that takes text from a text area and converts each individual character in the string into a random font.
This is my current attempt (which doesn't work):
<body>
<div class="container main-form">
<form>
<div class="form-group">
<label for="textinput">Input your text below</label>
<textarea class="form-control" id="textinput" rows="3"></textarea>
</div>
<button type="button" class="btn btn-outline-primary float-right" id="submit">Generate</button>
</form>
</div>
<div class="container output">
<script>
var input = "";
var ouput = "";
var inputarr = [];
// Array of fonts for span
var fontarr = ["font-family: MaxHand1, sans-serif", "font-family: MaxHand2, sans-serif", "font-family: MaxHand3, sans-serif"];
if document.getElementById('submit').clicked == true { // If button is clicked
input = document.getElementById('textinput'); // Set 'input' string to what was in the text area
inputarr = input.split(""); // Create an array of letters from input
for (i = 0; i < inputarr.length; i++) {
fontchange = fontarr[Math.floor((Math.random() * 3) + 1)]; // Choose a random font
output = (output + "<span style=\"" + fontchange + "\">" + inputarr[i] + "</span>"); // Add <span style="[fontchange]">inputarr[i]</span> to output string
}
document.getElementById(textoutput) = output; // Output string to line 45
}
</script>
<p id="textoutput"></p>
</div>
</body>
When I click submit, though, nothing appears on screen. I'm not sure if it's just because the string isn't being changed, or if it's just not updating the textoutput p tags.
There are couples of syntax errors in your code. document.getElementById('submit').clicked == true and document.getElementById(textoutput) = output and input = document.getElementById('textinput') <--- this will not return string(it will return whole tag). Try below code(I fixed error)
those changes from the previous answer plus you need to modify your Math.random call so you get 0,1,2 --> I did this using the % (mod) operator
var fontarr = ["font-family: courier new, sans-serif",
"font-family: comic sans, sans-serif",
"font-family: arial black, sans-serif"];
function change(){
var input = "";
var output = "";
input = document.getElementById('textinput').value;
for (i = 0; i < input.length; i++) {
fontchange = fontarr[Math.floor(((Math.random() * 3) + 1)%3)];
output += "<span style=\"" + fontchange + "\">" + input[i] + "</span>";
}
//console.log(output);
document.getElementById("textoutput").innerHTML = output;
}
<body>
<div class="container main-form">
<form>
<div class="form-group">
<label for="textinput">Input your text below</label>
<textarea class="form-control" id="textinput" rows="3"></textarea>
</div>
<button type="button" class="btn btn-outline-primary float-right" id="submit" onclick="change()">Generate</button>
</form>
</div>
<div class="container output">
<script>
</script>
<p id="textoutput"></p>
</div>
</body>

Categories

Resources