How to detect if previous line in a textarea is empty - javascript

Is it possible to detect the structure of a single line in a textarea. For example this is my textarea and it's contents
this is the first line in textarea
1234 this is the second line starting with 1234
this is the fourth line and the third line is empty
So I want to detect empty lines like line 3 and also detect the first 4 characters of a line like line 2. Is this possible with jQuery or JavaScript?

The value in textarea is simply a string, which you can split at newlines to get each line.
var arrayOfLines = $('textarea').val().split('\n');
var finalString = "";
var prevBoolean = false;
for (var i = 0; i < arrayOfLines.length; i++) {
var line = arrayOfLines[i];
if (line.length === 0) {
console.log("empty line");
} else {
// if the first 4 characters of the line are "1234" set prevBoolean to true
if (line.substring(0, 4) == "1234"){
finalString += line + "\n";
prevBoolean = true;
} else {
// add custom line, if the previous non-empty line started with "1234" and set prevBoolean back to false
if (prevBoolean == true) {
prevBoolean = false;
finalString += "custom line" + "\n";
} else {
finalString += line + "\n";
}
}
}
}
// set the value of the textarea to the finalString
$('textarea').val(finalString);

Much simpler, more concise solution using $.each() as we can iterate through the object, and check for empty lines and/or lines that begin with 1234:
const arr = $('textarea').val().split('\n');
$.each(arr, (k, v) => {
if (v.length === 0) console.log(k + ' is empty');
if (v.substring(0, 4) == 1234) console.log('1234 found in key: ' + k);
});

Related

Find specific character from string and change its position to previous character using javascript, jquery

Is it possible to Find specific character from string and change its position to previous character
for example: Let us say there is say a string: Kù Iù Mù
I want output like : ùK ùI ùM
Yes of course! You can go over the string in loop char by char, look at the next position and if it is the char U want, switch the position!
function switchChar(text, charToFind) {
//temp variable for building result
var result = "";
//loop over original string
for (var i = 0; i < text.length; i++) {
//chack not to jump out of array
if (i + 1 < text.length) {
//if next char is the char im looking for
if (text[i + 1] == charToFind) {
//write next char first
result += charToFind;
//then write original char
result += text[i];
//iterate i once more to jump over next char (I appended two chars in this single cycle)
i++;
//if it is not the char Im looking for
} else {
//write it down
result += text[i];
}
//I am at the end
} else {
//write the char
result += text[i];
}
}
return result;
}
console.log(switchChar('Kù Iù Mù', 'ù'))

JavaScript: How to flag words in a string to be shown in a different colour where each char of the string is appended to an element one by one?

I'm writing a function that takes in a string (e.g. "Hello World!") and appends each character of the string to an HTML element with a delay in between each character (i.e. creating a type writer effect).
I want to flag certain words in the string and colour it (e.g. "Hello") so that each character printed is coloured.
I've seen other examples of this but all of them have the string hardcoded or do not allow the colouring of certain words.
I've tried inserting characters (e.g. ☺) into the string as a flag and when I encounter these, I colour every letter until I encounter it again.
// start with this string
let originalStr = "Hello Wor☺ld";
// insert "☺" at the start and end of "Wor☺ld"
let str = "Hello ☺Wor☺ld☺!";
let isFlagged = false;
str = str.split("");
str.forEach(function(item){
if (item ==="☺" && !isFlagged){
isFlagged = true;
}else if (item === "☺" && isFlagged){
isFlagged = false;
}else if (isFlagged){
console.log(item + " red");
}else{
console.log(item);
}
});
Desired output is each char of "Wor☺ld" is logged with " red" appended to it.
Here, "Wor" is correctly flagged, but "☺ld" is not.
This works fine but breaks if "☺" already existed within the string and I'm wondering if there's a better way to handle the flagging of words.
You can try this:
let textString = "Hello ☺Wor☺ld. Hello, ☺world☺ !"
let reg = /☺(.*?)☺/ig
let ocurrences = Array.from(textString.matchAll(reg))
let ranges = ocurrences.map(ocurrence => {
return {
start: ocurrence.index,
end: ocurrence.index + ocurrence[1].length + 1
}
})
let parsedText = textString.split('').map((char, charIndex) => {
let rangesThatContainsChar = ranges.filter( range => {
return charIndex > range.start && charIndex < range.end
})
let isInside = rangesThatContainsChar.length === 0
return isInside ? char : char + ' red'
})
parsedText.forEach(char => console.log(char))
You need to set flage true instead of false in first else if condition. I hope it will help you.
let originalStr = "Hello Wor☺ld";
// insert "☺" at the start and end of "Wor☺ld"
var str = "Hello ☺Wor☺ld☺!";
let isFlagged = false;
str = str.split("");
str.forEach(function (item) {
if (item === "☺" && !isFlagged) {
isFlagged = true;
} else if (item === "☺" && isFlagged) {
isFlagged = true;
} else if (isFlagged) {
console.log(item + " red");
} else {
console.log(item);
}
});

How to maintain case and ignore spaces in Vigenere Cipher

I need to be able to keep the same case, i.e. "Attack" will be "Lxfopv", with the key "lemon". In addition, I need to keep any spaces within the message to be encrypted.
I used an if statement to check for whitespace
if(text.charAt(i) == ' '){
continue;
but it doesn't seem to do anything.
function encrypt(text, key) {
var output= '';
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(var i = 0; i < text.length; i++){
var a= alphabet.indexOf(key.charAt(i % key.length));
var b= alphabet.indexOf(text.charAt(i));
if(text.charAt(i) == ' '){
continue;
}else{
output += alphabet.charAt((a+ b) % alphabet.length);
}
}
return output;
}
if pass in "Attack at Dawn", my desired output should be Lxfopv ef Rnhr but I am recieving LxFopvmHOeIB with the key "lemon".
How can I fix this to get the desired output? Is it something to do with the fact that I have hardcoded my alphabet?
In order to keep the case, you will have to work your transformation on a single case.
Only at the time of adding it to your output, will you convert it to the correct case.
And in order to get the same value than other algorithms which do ignore the space character, you have to use a second iterator variable.
This iterator should get incremented only on valid inputs, and will be used to iterate the key.
inp.oninput = e => log.textContent = encrypt(inp.value, 'lemon');
function encrypt(text, key) {
var output= '';
// single case dictionary
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var low = text.toLowerCase(); // we'll work on this one
for(let i = 0, j = 0; i < text.length; i++){
// here we use `j` for the key
let a = alphabet.indexOf(key.charAt(j % key.length));
let b = alphabet.indexOf(low.charAt(i));
let out = ''; // the character we'll add
if(low.charAt(i) == ' '){
out = ' '; // keep spaces untouched
}else if(b > -1){ // only if valid
out = alphabet.charAt((a+ b) % alphabet.length); // get the ciphered value
j++; // only here we increment `j`
}
if(low[i] !== text[i]) { // if input and lower case are different
// that means that input was upper case
out = out.toUpperCase();
}
output += out;
}
return output;
}
<input id="inp"> <pre id="log"></pre>
Just add the space to your alphabet:
if(text.charAt(i) == ' '){
output += " ";
}

Add space to string when it includes word in array

I have a function where I am iterating through a given string, alternating the capitalisation of each character and concatenating it to variable alt.
In order to loop through this properly, I have removed spaces from the original string. But I need to add them back at the end of the function.
function alternatingCaps(str) { // 'hello world'
let words = str.toLowerCase().split(' '); // ['hello','world']
str = words.join(''); // 'helloworld'
let alt = '';
for(let i = 0; i < str.length; i++) {
if(i % 2 === 0)
alt += str[i].toUpperCase();
else
alt += str[i].toLowerCase();
}
return alt;
}
console.log(alternatingCaps('hello world'));
/* Output: "HeLlOwOrLd"
Wanted output: "HeLlO wOrLd" */
Once alt contains a string included as a value in the words array, I want to add a space at the end of the word.
Here was my attempt:
words.forEach(function(word) {
if(alt.toLowerCase().includes(word) && word[word.length - 1] === alt[i].toLowerCase())
alt += ' ';
});
It checks if any of the words in the words array are present in the alt string and if the current character iteration of the string corresponds to the last letter in the word. If so, it adds a space to the string.
But this does not work as intended.
> Output: "HeLlO wOr Ld"
> Wanted output: "HeLlO wOrLd"
I also imagine this would cause problems with duplicate letters. How can I accomplish my goal?
You shouldn't join your words. Keep them as separate elements in the words array then you can loop through that array applying you function to each element.
function alternatingCaps(str) { // 'hello world'
let words = str.toLowerCase().split(' '); // ['hello','world']
const alts = words.map(word => capitalizeEvens(word));
return alts.join(' ');
function capitalizeEvens(word) {
let alt = '';
for(let i = 0; i < word.length; i++) {
if(i % 2 === 0)
alt += word[i].toUpperCase();
else
alt += word[i].toLowerCase();
}
return alt;
}
console.log(alternatingCaps('hello world'));
You can iterate through your string one char at a time. Then, check whether the characters is an actual word character. If so, alternate the capitalization, if not, add it to the output as it is:
function altCaps(input) {
var result = '';
var cap = false;
for (var i = 0; i < input.length; i++) {
var c = input[i];
result += /\w/.test(c) ? (cap = !cap) ? c.toUpperCase() : c.toLowerCase() : c;
}
return result;
}
UPDATE: The legible code
function altCaps(input) {
var result = '';
var cap = false;
for (var i = 0; i < input.length; i++) {
var c = input[i];
if (/\w/.test(c)) { // check if char is a "word character" (i.e. letter)
cap = !cap; // toggle next capitalization
if (cap) // if it should capitalize
result += c.toUpperCase(); // add uppercase letter
else
result += : c.toLowerCase(); // add lowercase letter
} else {
result += c; // no letter, so add character as is.
}
}
return result;
}

Lossless compression run length encoding in javascript

For my assignment, I am writing the code to compress and then decompress a string through lossless compression in javascript.
For example-
Original string: heeeeelllllloo
Compressed: h1e5l6o2
Decompressed: heeeeelllllloo
This code comes out as an infinite loop, and the problem is somewhere in the compression function. Please help me find/solve the issue!
This is what I have so far:
// Read in the original text
var textToCompress = prompt("Enter the text you would like to compress: ");
runLengthEncoding(textToCompress);
function runLengthEncoding(originalText){
console.log("Original Text: " + originalText);
console.log("");
// Compress the text
console.log("COMPRESSING...");
var compressedText = compress(originalText);
console.log("Compressed: " + compressedText);
console.log("");
//Decompress the text
console.log("DECOMPRESSING...");
//var decompressedText = decompress(compressedText);
console.log("Decompressed: " + decompressedText);
console.log("");
// Make sure the compression was lossless
if(originalText == decompressedText)
{
console.log("Success! The decompressed text is the same as the original!");
}
}
// Compresses the original String by building up a new String
// with each character and how many times it repeats in a given run.
// Returns the compressed text.
function compress(original){
var result = "";
//Write your code here
for (var i = 1; i < original.length; i++){//look at each character in string
var sum = 1;
var currentChar = original.charAt(i);
//if currentchar is the first character
if (currentChar == original.charAt(0)){//isolate frist character of the string
result = currentChar;//add the currentchar to result
console.log(result);
//if currentchar is not the first character
} else if (currentChar !== original.charAt(0)) {
//if currentchar is equal to the previous character
if (currentChar == original.charAt(i-1)){
sum++;
} else {
result += sum;//add sum ot the result and reset sum to 1
sum = 1;
i = 0;
}
}
}
}
// Decompresses the compressed Run Length Encoded text back
// into the original form.
function decompress(compressedText)
{
var result = "";
for(var i = 0; i < compressedText.length; i += 2)
{
// Get the current run character
var character = compressedText.charAt(i);
// Get the run length
var runLength = parseInt(compressedText.charAt(i+1));
// Add that many repetitions of the original character to the result
for(var runIndex = 0; runIndex < runLength; runIndex++)
{
result += character;
}
}
return result;
}
First of all, don't compare the chars to find out if this char is the first one, because this would return true if the first char is repeated in the text.
The seond thing I saw, is that you set the index i to 0 every time you find a new character which leads your function to start at the beginning of the string again and will end in a deadlock.
Thats at least what I think, and I hope I could help you

Categories

Resources