Removing last comma - javascript

I read content from a file and then write it another file after editing . While editing , for each read line i put a comma at the end of line and then write it to the file. For the last read line i do not want to write a comma. How should i do it.?
while(!inputFile.AtEndOfStream){
var readLine = inputFile.ReadLine();
var omitChars = new RegExp("#define").test(readLine);
if(omitChars==1){
var stringReadPosition = readLine.substr(8);
var finalString = stringReadPosition.replace(/\s+/g, ': ');
asd = outputFile.Write(finalString.replace(/^(_)/, "") + ",\r\n");
}
}
outputFile.Write("};\r\n");
inputFile.Close();
outputFile.Close();
}

You can use substring in order to remove the last character of the string after you have formed the string:
finalString = finalString.substring(0, finalString.length - 1);
An alternative would be the use of slice, taking into consideration that negative indices are relative to the end of the string:
finalString = finalString.slice(0,-1);
Take a look in this question for more.
UPDATE: For your case, you could check whether or not you have reached the EOF - meaning you have read the last line, and then apply slice or substring:
//....
var stringReadPosition = readLine.substr(8);
var finalString = stringReadPosition.replace(/\s+/g, ': ');
//Check if stream reached EOF.
if(inputFile.AtEndOfStream) {
finalString = finalString.slice(0,-1);
}
asd = outputFile.Write(finalString.replace(/^(_)/, "") + ",\r\n");
//....

try this asd = asd.replace(/,\s*$/, "");
this will remove last comma, I have tried this, its working .Check if it works in ur code.
Try this code inside while loop

Related

How to replace all newlines after reading a file

How can I replace a newline in a string with a ','? I have a string that is read from a file:
const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);
It takes a string from a file:
a,b,c,d,e,f
,,,,,
g,h,i,j,k,l
I'm able to detect the newline with this:
if (char === '\n')
But replacing \n like this doesn't work
str = csvString.replace('/\n/g');
I want to get the string to look like this:
a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,
You can add , at end of each line like this
$ - Matches end of line
let str = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`
let op = str.replace(/$/mg, "$&"+ ',')
console.log(op)
Try replacing the pattern $ with ,, comma:
var input = 'a,b,c,d,e,f';
input = input.replace(/$/mg, ",");
console.log(input);
Since you intend to retain the newlines/carriage returns, we can just take advantage of $ to represent the end of each line.
let text = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`;
let edited = text.replace(/\s+/g, '');
console.log( edited )
You can try this solution also. \s means white spaces.
You may try out like,
// Let us have some sentences havin linebreaks as \n.
let statements = " Programming is so cool. \n We love to code. \n We can built what we want. \n :)";
// We will console it and see that they are working fine.
console.log(statements);
// We may replace the string via various methods which are as follows,
// FIRST IS USING SPLIT AND JOIN
let statementsWithComma1 = statements.split("\n").join(",");
// RESULT
console.log("RESULT1 : ", statementsWithComma1);
// SECOND IS USING REGEX
let statementsWithComma2 = statements.replace(/\n/gi, ',');
// RESULT
console.log("RESULT2 : ", statementsWithComma2);
// THIRS IS USING FOR LOOP
let statementsWithComma3 = "";
for(let i=0; i < statements.length; i++){
if(statements[i] === "\n")
statementsWithComma3 += ','
else
statementsWithComma3 += statements[i]
}
// RESULT
console.log("RESULT3 : ", statementsWithComma3);
I believe in some systems newline is \r\n or just \r, so give /\r?\n|\r/ a shot

Insert line break every 3 lines in javascript?

Hi I'm still a newbie at javascript so I want to create a script that inserts a line break after every 3 lines. So here's my code I got so far
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.toString().match(/.{3}/g).join('</br>');
console.log(newNum);
It is doing it wrong. It seems to be inserting every 3characters instead of lines. Can anyone help me fix the code?
You can use the replace function. Try the below code.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/(.*\n.*\n.*\n)/g, '$1<br>');
console.log(newNum);
EDIT
I have made a few changes to the RegEx in the code below. This will allow you to specify the number of lines between which <br> need to be added.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/((.*\n){3})/g, '$1<br>');
console.log(newNum);
In the above RegEx, the .* will match all characters till the end of line and the \n will match the new line character.
(.*\n){3}
I have enclosed this in parenthesis to mark it as a group and used {3} to indicate that the preceding group repeats 3 times.
((.*\n){3})
Then the whole RegEx is enclosed in a parenthesis to use it as the first matched group that can be referenced in the replace section using $1.
You can replace the {3} with any number.
You should avoid using string manipulation when using HTML string. Also using BR to break line is not a good idea as well. You should use a block element instead.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var content = document.querySelector('.content');
var urls = num.split('\n');
var temp;
for(var i = 0; i< urls.length; i++) {
if(!temp || (i+1) % 3 === 0) {
if (temp) content.appendChild(temp);
temp = document.createElement('div');
}
var span = document.createElement('span');
span.classList.add('link')
span.innerHTML = urls[i];
temp.appendChild(span);
}
content.appendChild(temp);
.link {
margin: 5px;
}
<div class='content'>
Reference:
Is it sometimes bad to use <BR />?

Google Apps Script---Replace Straight Quotation Marks with Curly Ones

When I was typing a novel on my Google Docs iPad app, it used straight up-and-down quotation marks, like this: ". Now, I want to change all of these quotes to the curly kind, without having to change all of them by hand.
I wrote a simple Google Apps Script file to deal with the issue, but when I run it, it seems to say "Running function myFunction..." indefinitely.
Here is my code. The first few lines deal with quotes in the middle of the sentence, using a simple replaceText method. Meanwhile, the while statement tests if there is a line break (\n) before the quote, and uses that to determine whether to put a beginning or end quote.
function myFunction() {
var body = DocumentApp.getActiveDocument().getBody();
//Replace quotes that are not at beginning or end of paragraph
body.replaceText(' "', ' “');
body.replaceText('" ', '” ');
var bodyString = body.getText();
var x = bodyString.indexOf('"');
var bodyText = body.editAsText();
while (x != -1) {
var testForLineBreaks = bodyString.slice(x-2, x);
if (testForLineBreaks == '\n') { //testForLineBreaks determines whether it is the beginning of the paragraph
//Replace quotes at beginning of paragraph
bodyText.deleteText(x, x);
bodyText.insertText(x, '“');
} else {
//Replace quotes at end of paragraph
bodyText.deleteText(x, x);
bodyText.insertText(x, '”');
}
x = bodyString.indexOf('"');
}
}
I can't seem to find what's wrong with it. And to confuse things more, when I click the debugger, it says
Too many changes applied before saving document. Please save changes in smaller batches using Document.saveAndClose(), then reopen the document with Document.openById().
I appreciate all help with this. Thank you in advance!
I am not sure about the exact limit, but I think you can include a counter in your while loop, and for every 50 or 100, output that via Logger.log(); once you get hold of that limit count, you may do what being suggested,
i.e. when approaching the limit, flush/save the changes by calling Document.saveAndClose(), then start again with the main loop by reopening the document with Document.openById()
some1 was right about the error message, but unfortunately that did not get to the root of the problem:
At the end of my while loop, the variable bodyString was being used to find the location of quotation marks to change. The problem was that bodyString was just that, a string, and so I needed to update it each time I made a change to the document.
Another problem, albeit more basic, was that Google counts \n as one character, so I had to change the parameter in var testForLineBreaks = bodyString.slice(x-2, x); to x-1, x.
After tinkering with these issues, my finished code looked like this:
function myFunction() {
var body = DocumentApp.getActiveDocument().getBody();
//Replace quotes that are not at beginning or end of paragraph
body.replaceText(' "', ' “');
body.replaceText('" ', '” ');
var bodyString = body.getText();
var x = bodyString.indexOf('"');
var bodyText = body.editAsText();
while (x != -1) {
var testForLineBreaks = bodyString.slice(x-1, x);
if (testForLineBreaks == '\n') { //testForLineBreaks determines whether it is the beginning of the paragraph
//Replace quotes at beginning of paragraph
bodyText.deleteText(x, x);
bodyText.insertText(x, '“');
} else {
//Replace quotes at end of paragraph
bodyText.deleteText(x, x);
bodyText.insertText(x, '”');
}
body = DocumentApp.getActiveDocument().getBody();
bodyString = body.getText();
x = bodyString.indexOf('"');
bodyText = body.editAsText();
}
}
There is one remaining problem with the code. If the quote is at the very beginning of the document, as in the first character, then the script will insert the wrong quote style. However, I plan on fixing that manually.

Remove part of String in JavaScript

I have a String like
var str = "test\ntesttest\ntest\nstringtest\n..."
If I reached a configured count of lines ('\n') in the string, I want to remove the first line. That means all text to the first '\n'.
Before:
var str = "test1\ntesttest2\ntest3\nstringtest4\n...5"
After:
var str = "testtest2\ntest3\nstringtest4\n...5"
Is there a function in Javascript that I can use?
Thanks for help!
Find the first occurence of \n and return only everything after it
var newString = str.substring(str.indexOf("\n") + 1);
The + 1 means that you're also removing the new-line character so that the beginning of the new string is only text after the first \n from the original string.
You could use string.replace function also.
> var str = "test1\ntesttest2\ntest3\nstringtest4\n...5"
> str.replace(/.*\n/, '')
'testtest2\ntest3\nstringtest4\n...5'
str.substr(str.indexOf("\n")+1)
str.indexOf("\n")+1 gets the index of the first character after your first linebreak.
str.substr(str.indexOf("\n")+1) gets a substring of str starting at this index
You could write a function like this if I understand you correctly
function removePart(str, count) {
var strCount = str.split('\n').length - 1;
if(count > strCount) {
var firstIndex = str.indexOf('\n');
return str.substring(firstIndex, str.length -1);
}
return str;
}
You could use the substring(..) function. It is built-in with JavaScript. From the docs:
The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
Usage:
mystring.substring(start,end)
The start index is required, the end index is not. If you omit the end index, it will substring from the start to the end of the string.
Or in your case, something like:
str = str.substring(str.indexOf('\n')+1);

Trim a variable's value until it reaches to a certain character

so my idea is like this..
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
var newString = myString.substr(4); // i want this to dynamically trim the numbers till it has reached the .
// but i wanted the 1. 13. 153. and so on removed.
// i have more value's in my array with different 'numbers' in the beginning
so im having trouble with this can anyone help me find a more simple solution which dynamically chop's down the first character's till the '.' ?
You can do something like
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
songList.forEach(function(value, i){
songList[i] = value.replace(/\d+\./, ''); //value.substr(value.indexOf('.') + 1)
});
Demo: Fiddle
You can use the string .match() method to extract the part up to and including the first . as follows:
var newString = myString.match(/[^.]*./)[0];
That assumes that there will be a match. If you need to allow for no match occurring then perhaps:
var newString = (myString.match(/[^.]*./) || [myString])[0];
If you're saying you want to remove the numbers and keep the rest of the string, then a simple .replace() will do it:
var newString = myString.replace(/^[^.]*. */, "");

Categories

Resources