Add line breaks around multiple uppercase words in a string [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Edited because i wasn't clear enough
I have some text from a .txt file, that i want to display on a HTML page. I want to have a linebreak before- and after an uppercase line, but not for standalone words. Like if more than 2 words are uppercase, they should be on a seperate line, but not if its only one word.
const text1 = "I want THIS ON A SEPERATE LINE but not THIS text here";
function convertText(text) {
...check for uppercase line....
document.write(modifiedText)
}
convertText(text1);
/*
Wanted result:
I want
THIS ON A SEPERATE LINE
but not THIS text here
*/
How can I do this?

You'll need to split each word up, put them into groups of capitalised and non-capitalised and then iterate through those groups, checking each word to find if there are multiple capitalised words in each group. Something like the following should do the job:
function convertText(text) {
const words = text.split(' '); // split the string into an array of word strings
let currentLine = '';
// groups of words of the same case
const wordGroups = [];
let lastWordWasAllCaps = false;
// group words by case
for (const word of words) {
if (word === word.toUpperCase()) {
if(!lastWordWasAllCaps) {
// word is in block capitals, but the last one wasn't
wordGroups.push(currentLine);
currentLine = word;
} else {
currentLine = currentLine.concat(' ', word);
}
lastWordWasAllCaps = true;
} else {
if (lastWordWasAllCaps) {
// word is not in block capitals, but the last one was
wordGroups.push(currentLine);
currentLine = word;
} else {
currentLine = currentLine.concat(' ', word);
}
lastWordWasAllCaps = false;
}
}
// push the last line
wordGroups.push(currentLine);
let finalString = '';
let breakNextLine = true;
// now look through the groups of words and join any single full capital words to their siblings
for (const wordGroup of wordGroups) {
// if a group is all caps and has no spaces, join it without a line break
if (wordGroup === wordGroup.toUpperCase() && !wordGroup.includes(' ')) {
finalString = finalString.concat(' ', wordGroup);
// tell the next set to join without a line break
breakNextLine = false;
} else {
if (breakNextLine) {
finalString = finalString.concat('\n', wordGroup);
} else {
finalString = finalString.concat(' ', wordGroup);
}
breakNextLine = true;
}
}
return finalString.slice(2); // remove the added spaces at the start
}

Related

Document document is not defined javascript in Google apps Script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 26 days ago.
Improve this question
I can't run my code in the Google Apps Script editor. Clicking Run gives the error document is undefined.
I am trying to create a function that separates a String into substrings using a separator character and returns those substrings in an array.
function splitSrt(str, delim) {
var word = "";
var num = 0;
str = str + delim;
var x = str.length;
var substr_list = [];
for( var i = 0; i < x; i++){
if(str[i] != delim)
word = word + str[i];
else{
if(word.length != 0)
substr_list.push(word);
word = "";
}
}
return substr_list;
}
var str = "hello my world";
var delim = ' ';
var res = splitSrt(str, delim);
res.forEach(a => {
document.write( a + "<br>");
});
The code you quote will not work in Apps Script because it is attempting to write to a web page through the DOM method document.write(), which is not available in server-side code such as Node.js or Apps Script.
The problem is "function that separates a String into substrings using a passable character and returns them in an array"
You probably do not need to write a function for that. Simply use String.split(), like this:
function test() {
const str = "hello my world";
const delim = ' ';
const res = str.split(delim);
res.forEach(word => {
console.log(word);
});
}
For more complex splitting, use a regular expression as the separator.
If you really need to create your own string splitter function, start with something like this:
function splitSrt(str, delim) {
return String(str).split(delim);
}

How to convert string to camelCase without using RegEX

I'm trying to do a challenge which is converting all strings into camelCase but without using regex, only using the methods like(split, slice, replace, includes.. etc). Some words have spaces and should remove them. Here's the CODE and I'm really STUCK. NOTE: the user enters the STRING and when user clicks the button should return to the camelCase.
INPUT =>
//underscore_case
//first_name
//Some_Variable
// calculate_AGE
//delayed_departure
OUTPUT =>
//underscoreCase
//firstName
//someVariable
//calculateAge
//delayedDeparture
document.body.append(document.createElement('textarea'));
document.body.append(document.createElement('button'));
document.querySelector('button').addEventListener('click', function() {
const text = document.querySelector('textarea').value;
const row = text.split('\n');
let [...n] = '';
for (const theText of row) {
const lowerText = theText.toLowerCase().trim();
if (lowerText.includes('_')) {
n = lowerText.replace('_', ' ');
console.log([...n]);
}
}
});
Explanation of this simple algorithm:
Your input must have words that split by a certain character, as you need something to identify which part of the string is a word. Let's assume your string has words separated by '//' instead of spaces as you mentioned in the comments, and each of those words is split by '_'.
First you need to split all words in the string into an array, you can use the split() method in order to do that.
Then when iterating through each word, split it again with split() but this time with whatever identifies the different words, in our case it's _.
Iterate through each split words, if it's the first word lowercase it using toLowerCase() and add it to the new word variable, if not, lowercase it and capitalize the first letter.
And that's it. Here's the implementation:
const inputWithoutCamelCase = 'hello_world // HOW_ARE_YOU // foo_BAR'
function stringToCamelCase(string) {
const allNames = string.split('//')
let camelCasedString = '';
for (const name of allNames) {
camelCasedString += nameToCamelCaseHelper(name);
}
return camelCasedString;
}
function nameToCamelCaseHelper(word) {
const splittedName = word.split('_');
let camelCasedName = '';
for (let i = 0; i < splittedName.length; i++) {
if (i === 0) {
camelCasedName += splittedName[i].toLowerCase();
} else {
camelCasedName += capitalizeFirstLetter(splittedName[i].toLowerCase())
}
}
return camelCasedName;
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
stringToCamelCase(inputWithoutCamelCase) // helloWorld howAreYou fooBar

SyntaxError: Unterminated parenthetical, how to handle "( )" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to clean up a string (anything that contains unwanted characters, diacritics, etc.) entered by a user and replace with just one string with no spaces.
I came across this error:
Execution failed: SyntaxError: Unterminated parenthetical.
It stopped at this line: idoff = accented.search(a2.charAt(i));
I was able to update our old legacy code when we encountered several accented letters (diacritics). I saw a code that I could use to resolve it but somehow I cannot figure out to how fix this one.
function clean(a2) {
/* if string contains accented letters, index below and use regular text */
var accented = 'ÁÀÂÃÄÄÅÆáàâãäåąÇçćčÐÉÉÊËèéêëðęÍÍÎÏíîïłÑñńÖÓŐÓÔÕØöóőôõøÜŰÙÚÛÜüűúûŠšŸÿýŽžŻżŁ';
var regularText = 'AAAAAAAAaaaaaaaaCcccDEEEEeeeeeeIIIIiiilNnnOOOOOOOooooooUUUUUUuuuuSSYyyZzZzL';
var idoff = -1,new_text = '';
var lentext = a2.toString().length -1
for (i = 0; i <= lentext; i++) {
idoff = accented.search(a2.charAt(i));
if (idoff == -1) {
new_text = new_text + a2.charAt(i);
} else {
new_text = new_text + regularText.charAt(idoff);
}
}
// return new_text;
/* Locate where in the string that contains ":", remove it including spaces and change string to lowercase */
var space = new_text.indexOf(":");
if (space > -1) {
var answer = new_text.substring(space);
answer = answer.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()"'+#<>?]/g,"")
answer = answer.replace(/ /g,"");
answer = answer.toLowerCase();
} else {
var answer = new_text;
answer = answer.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()"'+#<>?]/g,"")
answer = answer.replace(/ /g,"");
answer = answer.toLowerCase();
}
return answer;
}
If string is like this ABC-XYZ-LMN (AB12): XxxX Set Çompanÿ I want to clean it up to this xxxxsetcompany.
String.prototype.search expects a regular expression, but you're passing in a character (string). As you iterate over a2 you eventually come across an open parenthesis (the one surrounding "AB12"). An open parenthesis is not a valid regex.
To fix this you could use String.prototype.includes instead.
However, I think a more elegant solution to your issue may look something like this:
function clean(a2) {
/* if string contains accented letters, index below and use regular text */
const accented = 'ÁÀÂÃÄÄÅÆáàâãäåąÇçćčÐÉÉÊËèéêëðęÍÍÎÏíîïłÑñńÖÓŐÓÔÕØöóőôõøÜŰÙÚÛÜüűúûŠšŸÿýŽžŻżŁ';
const regularText = 'AAAAAAAAaaaaaaaCcccDEEEEeeeeeeIIIIiiilNnnOOOOOOOooooooUUUUUUuuuuSSYyyZzZzL'.split('');
let answer = '';
a2.split('').forEach((char) => {
let accentIndex = accented.indexOf(char);
if (accentIndex > -1) {
answer += regularText[accentIndex];
} else {
answer += char;
}
});
answer = answer.replace(/\W/gi, '');
return answer.toLowerCase();
}
console.log(clean('ABC-XYZ-LMN (AB12): XxxX Set Çompanÿ'));
Add the code after function clean(a2) {
var name = name;
name = name.replace(/[\])}[{(]/g, '');
name = name.toLowerCase();
...

How to remove the blank lines in a textarea with JavaScript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I get the content of a textarea with:
var stringArray = document.getElementById('textarea').value;
I must remove all blank lines (even blank lines with spaces). What is an efficient way to do that?
EDIT: I want to remove the blank lines, not the whitespace.
e.g.
A
B
C
D
to
A
B
C
D
Finally I managed to make it work. This is the code just in case someone else would need it:
function delBlankLines() {
var stringArray = document.getElementById('textarea').value.split('\n');
var temp = [""];
var x = 0;
for (var i = 0; i < stringArray.length; i++) {
if (stringArray[i].trim() != "") {
temp[x] = stringArray[i];
x++;
}
}
temp = temp.join('\n');
document.myform.textarea.value = temp;
}
So, the textarea content is split into a string array, that array is looped and checked if the trimmed current line is blank; if it's not, the line is copied to a temporary string array (basically the blank lines are ignored). At the end, I update the textarea with the temporary string array.
you can use the native JavaScript trim method (available on the string prototype): textareaValue.trim().
Trivia: there's automatic setting of window.textarea to be document.getElementById('textarea'). So you can access that by just doing textarea. Therefore to access the textual content of the textarea you can use: textarea.innerHTML or const textAreaValue = textarea.value.
Next, run textAreaValue.trim(); this will get rid of any outer white space. " \n\n textArea \n\n\t\n " will turn into just "textArea".
Ok now we can split on new lines: const stringArray = textAreaValue.split('\n'). Since \n is the carriage return aka new line symbol.
Next, we'll want to skip any lines which have nothing but whitespace which we can probably find in a few ways but to be safest \S should work. To test out different regexes I recommend: regex101.com.
For a more modern version:
textarea.value = `
the
quick
brown
fox
jumped
over the lazy
dog.
`;
/*
function oldSolution() {
var cleanedString = '';
console.log(textarea.value);
var stringArray = textarea.value.trim().split('\n');
for(var i = 0; i < stringArray.length; i++){
var line = stringArray[i];
if(line.match('/\S/') !== -1){
cleanedString += line.trim();
}
}
console.log(cleanedString);
output.innerText = cleanedString;
return cleanedString;
}
*/
const cleanText = () => {
const stringArray = textarea.value
.trim()
.split('\n')
.filter(line => /\S/.test(line));
console.log({stringArray})
const cleanedString = stringArray.map(line => line.trim()).join(' ');
console.log(cleanedString);
output.innerText = cleanedString;
return cleanedString;
}
<textarea rows='5' cols='50' id='textarea'></textarea>
<input type='button' value='Extract Text' onclick='cleanText()'/>
<div id="output"></div>

Reverse words in array string matching punctuation in Javascript

How do I reverse the words in this string including the punctuation?
String.prototype.reverse = function () {
return this.split('').reverse().join('');
}
var str = "This is fun, hopefully.";
str.reverse();
Currently I am getting this:
".yllufepoh ,nuf si sihT"
When I want to return this:
"sihT si nuf, yllufepoh."
You could reverse each word instead of the whole string, but you have to keep spaces, periods etc seperate, so a word boundary is needed
String.prototype.reverse = function () {
return this.split(/\b/g).map(function(word) {
return word.split('').reverse().join('');
}).join('');
}
var str = "This is fun, hopefully.";
document.body.innerHTML = str.reverse();
Note that this moves the comma one space as it gets the comma and the space in one boundary and swaps them. If the comma needs to stay in the same spot, split on spaces as well, and change the regex to /(\b|\s)/g
Simply reversing the string wont give the solution.
Get each word.
Reverse It
Again rejoin
var str = "This is fun, hopefully.";
alert(str.split("").reverse().join("").split(" ").reverse().join(" "));
You can imagine that you receive a stream of letters and you have to construct words based on some separators (like: spaces, commas, dashes .etc).
While reading each character you keep constructing the word in reverse.
When you hit any separator you finished the word.
Now you just add it to the result and append the separator (this way the separators will not be put at the beginning of the word, but at the end).
Here is an example:
const inputString = "HELLO, Welcome to Google's meeting. My name is Jean-Piere... Bye";
console.log('Normal words: ', inputString);
const result = reverseWords(inputString);
console.log('Words reversed: ', result);
function reverseWords(str='', separators=' ,.-') {
let result = '';
let word = '';
for (const char of str) {
if (separators.includes(char)) {
result += word + char;
word = '';
} else {
word = char + word;
}
}
// Adds last remaining word, if there is no separator at the end.
result += word;
return result;
}
const str = "This is fun, hopefully.";
function reverseWords(str){
const tempArr= str.split(" ")
let reversedTempArr=''
for(let i=0; i<tempArr.length;i++){
let tempStr=''
for(let j=tempArr[i].length-1;j>=0;j--){
tempStr += tempArr[i][j]
}
reversedTempArr += tempStr+ " "
}
return reversedTempArr
}
console.log(reverseWords(str))
You can reverse each word in a string in squence by splitting that word in to an array of words and then reversing each word and storing it in a new array and then joining that array as shown below.
//1) Reverse words
function reverseWords(str) {
// Go for it
let reversed;
let newArray=[];
reversed = str.split(" ");
for(var i = 0;i<reversed.length; i++)
{
newArray.push(reversed[i].split("").reverse().join(""));
}
return newArray.join(" ");
}
let reversedString = reverseWords("This is fun, hopefully.");
console.log("This is the reversed string : ",reversedString);

Categories

Resources