How to add new item into srt file - javascript

This is start of a srt file:
0
00:00:07,000 --> 00:01:00,000
lorem ipsum... // this line doesn't work
1
00:01:02,960 --> 00:01:05,800
lorem ipsum...
2
00:01:05,840 --> 00:01:08,960
lorem ipsum...
The first line doesn't work, I suppose because of0 as the ordinal.
I need a way, javascript way if possible, to correctly change all ordinal numbers at once, not one by one (over 1000 lines), starting with 1 and not with 0.
I was searching for various online solutions, without success.

You could create an html file with a textarea, load it in your browser and copy
the contents of the .srt file in. Use the following javascript to convert the textarea's text:
var numberRegex = /^\d\s*$/;
var originalLines = text.split('\n');
var lines = [];
for (var index = 0; index != originalLines.length; ++index)
{
var orig = originalLines[index];
var match = numberRegex.exec(orig);
lines.push(match ? parseInt(orig) + 1 : orig);
}
Then the converted text you want is provided by:
lines.join('\n')

Related

Find the index of a string in Javascript with help of first three characters

I have numerous tsv files each with header row. Now one column name in header row is age. In few files, column name is age while in other files it has EOL charcter such as \r \n.
Now how can i use str.indexOf('age') function so that i get index of age irrespective of column name age with EOL character such as \n , \r etc..
Foe eg:
tsv file1:
Name Address Age Ph_Number
file 2:
Name Address Age/r
file 3:
Name Address Age\n
I am trying to find index of age column in each files header row.
However when i do-
header.indexOf('age')
it gives me result only in case of file1 because in other 2 files we have age as age\r and age\n..
My question is how should i find index of age irrespective of \r \n character along with age in header row.
i have following script now:
var headers = rows[0].split('\t');
if (file.name === 'subjects.tsv'){
for (var i = 0; i < rows.length; i++) {
var ageIdColumn = headers.indexOf("age");
console.log(headers)
As I stated in the comments, indexOf() returns the starting position of the string. It doesn't matter what comes after it:
var csvFile1 = 'column1,column2,column3,age,c1r1';
var csvFile2 = 'column1,column2,column3,age\r,c1r1';
var csvFile3 = 'column1,column2,column3,age\n,c1r1';
console.log(csvFile1.indexOf("age"));
console.log(csvFile2.indexOf("age"));
console.log(csvFile3.indexOf("age"));
If you specifically want to find the versions with the special characters, just look for them explicitly:
var csvFile4 = 'column1,age\r,column2,column3,age\n,c1r1';
console.log(csvFile4.indexOf("age\r"));
console.log(csvFile4.indexOf("age\n"));
Lastly, it may be that you are confused as to what, exactly indexOf() is supposed to do. It is not supposed to tell you where all occurrences of a given string are. It stops looking after the first match. To get all the locations, you'd need a loop similar to this:
var csvFile5 = 'column1,age\r,column2,age, column3,age\n,c1r1';
var results = []; // Found indexes will be stored here.
var pos = null; // Stores the last index position where "age" was found
while (pos !== -1){
// store the index where "age" is found
// If pos is not null, then we've already found age earlier and we
// need to start looking for the next occurence 3 characters after
// where we found it last time. If pos is null, we haven't found it
// yet and need to start from the beginning.
pos = csvFile5.indexOf("age", pos != null ? pos + 3 : pos );
pos !== -1 ? results.push(pos) : "";
}
// All the positions where "age" was in the string (irrespective of what follows it)
// are recorded in the array:
console.log(results);

Using Substring in javascript to collect values in a array

I have data in a single field which is as below:
40-818-938 | COUPLING, 25MM, PVC BLACK | PCS, MTR, BUNDLE | 3
The first block is the item code, second is the item description, third are the units, they are dynamic, and fourth is the number of units. The blocks are separated by |
I want to loop through the third block (units) and put them into separate variables without commas and spaces and use them to populate a select list.
Kindly help me in achieving that. Below is the code which adds the third block into a select list according to the number of units (fourth block), I need to separate them.
for (var i = 0; i < arrData[3]; i++) {
var x = document.createElement("OPTION");
x.setAttribute("value", arrData[2]);
var t = document.createTextNode(arrData[2]);
x.appendChild(t);
input.appendChild(x);
}
Thanks in advance.
Since you've already split the original string into an array, you just need to also split the 2nd element of that array:
arrData[2] = arrData[2].split(',');
Then, inside the loop, you need to reference it like so:
x.setAttribute("value", arrData[2][i]);
var t = document.createTextNode(arrData[2][i]);
Demo
Var items = obj.split("|");
Var units = items[2].split(",");
If you want to remove the spaces as well, you can add them to the pattern to split on:
var data = '40-818-938 | COUPLING, 25MM, PVC BLACK | PCS, MTR, BUNDLE | 3';
var units = data.split(/\s*\|\s*/g)[2]; // "PCS, MTR, BUNDLE"
console.log(units.split(/\s*,\s*/)[1]); // "MTR"
and the simplest way to make an option element is to use the Option constructor:
var unit = units.split(/\s*,\s*/)[1];
var x = new Option(unit, unit);
input.appendChild(x);
You need to use split function of java script. Ex.
var newstring=string.split('|');
var laststring=newstring[2].split(",");// new string
var yourneed=laststring[1];
you can do it this way
var string1 = yourstring.split('|');
var array = string1[2] .split(',');
Build a select:
array.forEach(function(entry) {
var x = document.createElement("OPTION");
x.setAttribute("value", entry);
var t = document.createTextNode(entry);
x.appendChild(t);
input.appendChild(x);
});

javascript removing characters from multiple strings using a for loop

I'm reading a log file using file reader and then want to do some text manipulation using javascript, to use the read data further in my program. So far I managed to split my input by lines, but now that I want to format the specific strings in the array nothing happens. Is this due to not declaring the array globally? Basically I wanted to do a for loop that checks all the strings inside my array and remove " " (four blank spaces) that appear at the start for some of my strings. This is my code
$("#draftlog").change(function() {
var logFile = $('#draftlog').get(0).files[0];
//gets first file from draftlog
var reader = new FileReader;
reader.readAsText(logFile);
reader.onload = function(e) {
var rawLog = reader.result;
//reads first file from draftlog as text
var re=/\r\n|\n\r|\n|\r/g;
arrayOfLines = rawLog.replace(re,"\n").split("\n");
//splits the text into an array of strings for every new line
for(x=0;x<arrayOfLines.length;x++) {
arrayOfLines[x].replace(/ /g,'');
}
console.log(arrayOfLines);
};
});
my input will typicaly look like this:
Event #: 7952945
Time: 5.2.2015 17:14:54
Players:
TheDoktorJot
Arlekin
Jokulgoblin
Felo
Petrolit
Greyjoy
--> Susti
themuse1975
n0sfea
------ FRF ------
Pack 1 pick 1:
Abzan Runemark
Rakshasa's Disdain
Reach of Shadows
Grim Contest
Aven Skirmisher
Lotus Path Djinn
Formless Nurturing
Tasigur's Cruelty
Temur Battle Rage
Return to the Earth
--> Temur Sabertooth
Fascination
Jeskai Barricade
Arcbond
Rugged Highlands
Pack 1 pick 2:
Sandblast
Sultai Runemark
Jeskai Sage
Hooded Assassin
Pressure Point
Gore Swine
Whisperer of the Wilds
Mardu Runemark
Ambush Krotiq
Write into Being
Qarsi High Priest
Hewed Stone Retainers
Wardscale Dragon
--> Mastery of the Unseen
Strings are immutable, you have to write it back
for(x=0;x<arrayOfLines.length;x++) {
arrayOfLines[x] = arrayOfLines[x].replace(/ /g,'');
}
You could also just trim it to remove leading and following whitespace
arrayOfLines[x] = arrayOfLines[x].trim();

Replacing Stings, Index (-1) value must be greater or equal to zero.?

I'm getting the following error in my app's script when replacing strings in a template file to generate reports.
Index (-1) value must be greater or equal to zero.
The function is listed bellow.
/**
* Search a String in the document and replaces it with the generated newString, and sets it Bold
*/
function replaceString(doc, String, newString) {
var ps = doc.getParagraphs();
for(var i=0; i<ps.length; i++) {
var p = ps[i];
var text = p.getText();
//var text = p.editAsText();
if(text.indexOf(String) >= 0) {
//look if the String is present in the current paragraph
//p.editAsText().setFontFamily(b, c, DocumentApp.FontFamily.COMIC_SANS_MS);
p.editAsText().replaceText(String, newString);
// we calculte the length of the string to modify, making sure that is trated like a string and not another ind of object.
var newStringLength = newString.toString().length;
// if a string has been replaced with a NON empty space, it sets the new string to Bold,
Logger.log([newString,newStringLength]);
if (newStringLength > 0) {
// re-populate the text variable with the updated content of the paragraph
text = p.getText();
Logger.log(text);
p.editAsText().setBold(text.indexOf(newString), text.indexOf(newString) + newStringLength - 1, true);
}
}
}
}
When it errors out
[newString,newStringLength] = [ The Rev Levels are at ZGS 003 on the electric quality standard. The part has a current change to ZGS 005!,108]
Does anyone have any suggestions?
Thanks in advance,
Michael
You are not handling the case where the string isnt there. Thus indexOf returns -1 and you use that. Also dont use reserved words like String for variable names.

How to get the number of lines in a textarea?

What I would like is to count the number of lines in a textarea, e.g:
line 1
line 2
line 3
line 4
should count up to 4 lines. Basically pressing enter once would transfer you to the next line
The following code isn't working:
var text = $("#myTextArea").val();
var lines = text.split("\r");
var count = lines.length;
console.log(count);
It always gives '1' no matter how many lines.
The problem with using "\n" or "\r" is it only counts the number of returns, if you have a line that is long it could wrap and then it wouldn't be counted as a new line. This is an alternative way to get the number of lines - so it may not be the best way.
Edit (thanks alex):
Script
$(document).ready(function(){
var lht = parseInt($('textarea').css('lineHeight'),10);
var lines = $('textarea').attr('scrollHeight') / lht;
console.log(lines);
})
Update: There is a much more thorough answer here: https://stackoverflow.com/a/1761203/145346
If you are just wanting to test hard line returns, this will work cross platform:
var text = $("#myTextArea").val();
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length;
console.log(count); // Outputs 4
I have implemented the lines and lineCount methods as String prototypes:
String.prototype.lines = function() { return this.split(/\r*\n/); }
String.prototype.lineCount = function() { return this.lines().length; }
Apparently the split method will not count a carriage return and/or newline character at the end of the string (or the innerText property of a textarea) in IE9, but it will count it in Chrome 22, yielding different results.
So far I have accomodated for this by subtracting 1 from the line count when the browser is other than Internet Explorer:
String.prototype.lineCount = function() { return this.lines().length - navigator.userAgent.indexOf("MSIE") != -1); }
Hopefully someone has a better RegExp or another workaround.
user \n instead of \r
var text = $("#myTextArea").val();
var lines = text.split("\n");
var count = lines.length;
console.log(count);
However this is working if you need use it because it respond to your problem
let text = document.getElementById("myTextarea").value;
let lines = text.split(/\r|\r\n|\n/);
let count = lines.length;
console.log(count);
What about splitting on "\n" instead?
It will also be a problem where one line wrapped to 2 lines in the textarea.
To do it accurately like this, you could use a fixed height font and measure pixels. This could be problematic though.
This function counts the number of lines which have text in a textarea:
function countLine(element) {
var text = $(element).val();
var lines = text.split("\n");
var count = 0;
for (var i = 0; i < lines.length-1; i++) {
if (lines[i].trim()!="" && lines[i].trim()!=null) {
count += 1;
}
}
return count;
}
Counting the newlines is not a reliable way for finding the number of lines, since long text could simply break and still only count as a single line.
What you want to do, is find out the scrollHeight of the textarea and divide it by the height of a single line.
This is answered in detail here:
https://stackoverflow.com/a/1761203/9863305
I've used the original answer of Mottie but some functions were changed in the JQuery API. Here is the working function for the current API v3.1.0:
var lht = parseInt($('#textarea').css('lineHeight'),10);
var lines = $('#textarea').prop('scrollHeight') / lht;
console.log(lines);
All tumbs up for Mottie's answer!
This will aim to consider lines with both hard and soft returns:
//determine what the fontsize will be
let fontsize = 12;
//get number of characters that can fit in a row
let charsperrow = textarea.clientWidth / fontsize;
//get any hard returns
let hardreturns = textarea.textContent.split(/\r|\r\n|\n/);
let rows = hardreturns.length;
//loop through returns and calculate soft returns
for(let i = 0,len = rows; i < len; i++){
let line = hardreturns[i];
let softreturns = Math.round(line.length / charsperrow);
//if softreturns is greater than 0, minus by 1 (hard return already counted)
softreturns = Math.round(softreturns > 0 ? (softreturns - 1) : 0);
rows += softreturns;
}
console.log(Math.round(rows));
The normal newline character is "\n". The convention on some systems is to also have "\r" beforehand, so on these systems "\r\n" is often found to mean a new line. In a browser, unless the user intentionally enters a "\r" by copying it from somewhere else, the newline will probably be expressed as just "\n". In either case splitting by "\n" will count the number of lines.
<html>
<head>
<script>
function countLines(theArea){
var theLines = theArea.value.replace((new RegExp(".{"+theArea.cols+"}","g")),"\n").split("\n");
if(theLines[theLines.length-1]=="") theLines.length--;
theArea.form.lineCount.value = theLines.length;
}
</script>
</head>
<body>
<form>
<textarea name="myText" onKeyUp="countLines(this)" cols="10" rows="10">
</textarea>
<br>
Lines:
<input type=text name="lineCount" size="2" value="0">
</form>
</body>
</html>
Your ans can be done in very simple way.
var text = $("#myTextArea").val();
// will remove the blank lines from the text-area
text = text.replace(/^\s*[\r\n]/gm, "");
//It will split when new lines enter
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length; //now you can count thses lines.
console.log(count);
This code for exact lines filled in the textarea.
and will work for sure.
Instead of textarea you could use a div with the attribute contenteditable="true". On a div with this attribute you can write anything, just like in a textarea, but any new line (except the first) is automatically wrapped inside a div. You can use jQuery or JS to count the div's and add +1, which is the first line.
It's a no brainer, i would use this instead of textarea with every occasion. It has several advantages. It auto resizes, you can easily count blank lines, you can customize every div or add spans with colors or font sizes or anything, you can use any line-height and any font-size, you can add rich text features and more, it's better for SEO and more. Here is a working example with jQuery:
$("#Editor").on("keyup mouseup", function(){
blankSpace = $(this).find("br").length; //count blank lines
urlCounter = $(this).find("div").length + 1 - blankSpace;
$(".lineCounter").text("Number of links: "+ urlCounter);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Editor" contenteditable="true" style="color:aqua;width: 100%;height: 100%;background: blue;"></div>
<div class="lineCounter" style="position: absolute;bottom: 0;z-index: 999;left: 0;"></div>
Try calling this function every time you change its value.
textArea.addEventListener('input', function() {
setDynamicHeight();
});
function setDynamicHeight() {
textArea.style.height = 0; // set the height to 0 in case of it has to be shrinked
textArea.style.height = textArea.scrollHeight + 'px'; // set the dynamic height
}
Each line break is defined by '\n'. The goal is to count them. For this, we will have to iterate on this with a loop on each character. See the example below
let count = 0
const a = document.querySelector('textarea')
for (let i = 0; i < a.value.length; i++) {
if (a.value[i] == '\n') {
count++
}
}
console.log(count)
In this live demonstration we can see a concrete case with 3 sentences :
const textareaLineCount = () => {
let count = 0
const a = document.querySelector('textarea')
for (let i = 0; i < a.value.length; i++) {
if (a.value[i] == '\n') {
count++
}
}
return count
}
const displayTotalTextareaLine = (total) => {
document.querySelector('p').innerText = total
}
document.querySelector('button').addEventListener('click', () => {
const total = textareaLineCount()
displayTotalTextareaLine(total)
})
<textarea>
Lorem ipsum dolor sit amet.
Lorem ipsum dolor sit amet.
Lorem ipsum dolor sit amet.
</textarea>
<button>count</button>
<p></p>
⚠️ It's possible that the last phase is not a line break, so I advise you to add 1 to the total result

Categories