check whether string contains a line break - javascript

So, I have to get HTML of textarea and check whether it contains line break. How can i see whether it contain \n because the string return using val() does not contain \n and i am not able to detect it. I tried using .split("\n") but it gave the same result. How can it be done ?
One minute, IDK why when i add \n to textarea as value, it breaks and move to next line.

Line breaks in HTML aren't represented by \n or \r. They can be represented in lots of ways, including the <br> element, or any block element following another (<p></p><p></p>, for instance).
If you're using a textarea, you may find \n or \r (or \r\n) for line breaks, so:
var text = $("#theTextArea").val();
var match = /\r|\n/.exec(text);
if (match) {
// Found one, look at `match` for details, in particular `match.index`
}
Live Example | Source
...but that's just textareas, not HTML elements in general.

var text = $('#total-number').text();
var eachLine = text.split('\n');
alert('Lines found: ' + eachLine.length);
for(var i = 0, l = eachLine.length; i < l; i++) {
alert('Line ' + (i+1) + ': ' + eachLine[i]);
}

You can simply use this
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;

Related

How can I get the official Unicode name of a character in Javascript from either its string or numeric value? [duplicate]

I need to find out the names for Unicode characters when the user enters the number for it. An example would be to enter 0041 and get given "Latin Capital Letter A" as the result.
As far as I know, there isn't a standard way to do this. You could probably parse the UnicodeData.txt file to get this information.
Here should be what you're looking for. The first array is simply http://unicode.org/Public/UNIDATA/Index.txt with replacing newlines with |;
// this mess..
var unc = "A WITH ACUTE, LATIN CAPITAL LETTER 00C1| /*... really big array ...*/ |zwsp 200B";
var uncs=unc.split("|");
var final_a = [];
var final_s = "";
for each (var item in uncs) {
var _T=item.split("\t");
//final_a [_T[1]] = _T[0];
final_s += '"' + _T[1] + '"' + ' : ' + '"' + _T[0] + '",';
}
console.log (final_s);
// yields..
var unicode_lookup = { /*really big array*/ }
// which we can use like so ...
alert(unicode_lookup["1D01"]);
// AE, LATIN LETTER SMALL CAPITAL
SO doesn't preserve tabs so the first part may not work if you simply copy-paste it. You'll note that some characters are duplicates so you may want to do some cleanup.

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.

How to detect line breaks in a text area input?

What is the best way to check the text area value for line breaks and then calculate the number of occurrences, if any?
I have a text area on a form on my webpage. I am using JavaScript to grab the value of the text area and then checking its length.
Example
enteredText = textareaVariableName.val();
characterCount = enteredText.length; // One line break entered returns 1
If a user enters a line break in the text area my calculation above gives the line break a length of 1. However I need to give line breaks a length of 2. Therefore I need to check for line breaks and the number of occurrences and then add this onto the total length.
Example of what I want to achieve
enteredText = textareaVariableName.val();
characterCount = enteredText.length + numberOfLineBreaks;
My solution before asking this question was the following:
enteredText = textareaVariableName.val();
enteredTextEncoded = escape(enteredText);
linebreaks = enteredTextEncoded.match(/%0A/g);
(linebreaks != null) ? numberOfLineBreaks = linebreaks.length : numberOfLineBreaks = 0;
I could see that encoding the text and checking for %0A was a bit long-winded, so I was after some better solutions. Thank you for all the suggestions.
You can use match on the string containing the line breaks, and the number of elements in that array should correspond to the number of line breaks.
enteredText = textareaVariableName.val();
numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
characterCount = enteredText.length + numberOfLineBreaks;
/\n/g is a regular expression meaning 'look for the character \n (line break), and do it globally (across the whole string).
The ||[] part is just in case there are no line breaks. Match will return null, so we test the length of an empty array instead to avoid errors.
Here's one way:
var count = text.length + text.replace(/[^\n]/g, '').length;
Alternatively, you could replace all the "naked" \n characters with \r\n and then use the overall length.
I'd do this using a regular expression:
var inTxt = document.getElementById('txtAreaId').value;
var charCount = inTxt.length + inTxt.match(/\n/gm).length;
where /\n/ matches linebreaks (obviously), g is the global flag. m stands for mult-line, which you evidently need in this case...Alternatively, though as I recall this is a tad slower:
var charCount = inTxt.length + (inTxt.split("\n").length);
Edit
Just realized that, if no line breaks are matched, this will spit an error, so best do:
charCount = intTxt.length + (inTxt.match(/\n/) !== null ? inTxt.match(/\n/gm).length : 0);
Or something similar...
For new JS use encodeURI(), because escape() is deprecated in ECMAScript 1.5.
Instead use:
enteredText = textareaVariableName.val();
enteredTextEncoded = encodeURI(enteredText);
linebreaks = enteredTextEncoded.match(/%0A/g);
(linebreaks != null) ? numberOfLineBreaks = linebreaks.length : numberOfLineBreaks = 0;
You can split the text based on new lines:
let textArray = text.split(/^/gm)
console.log(textArray.length)

Replace leading spaces with in Javascript

I have text like the following, with embedded spaces that show indentation of some xml data:
<Style id="KMLStyler"><br>
<IconStyle><br>
<colorMode>normal</colorMode><br>
I need to use Javascript to replace each LEADING space with
so that it looks like this:
<Style id="KMLStyler"><br>
<IconStyle><br>
<colorMode>normal</colorMode><br>
I have tried a basic replace, but it is matching all spaces, not just the leading ones. I want to leave all the spaces alone except the leading ones. Any ideas?
JavaScript does not have the convenient \G (not even look-behinds), so there's no pure regex-solution for this AFAIK. How about something like this:
function foo() {
var leadingSpaces = arguments[0].length;
var str = '';
while(leadingSpaces > 0) {
str += ' ';
leadingSpaces--;
}
return str;
}
var s = " A B C";
print(s.replace(/^[ \t]+/mg, foo));
which produces:
A B C
Tested here: http://ideone.com/XzLCR
EDIT
Or do it with a anonymous inner function (is it called that?) as commented by glebm in the comments:
var s = " A B C";
print(s.replace(/^[ \t]+/gm, function(x){ return new Array(x.length + 1).join(' ') }));
See that in action here: http://ideone.com/3JU52
Use ^ to anchor your pattern at the beginning of the string, or if you'r dealing with a multiline string (ie: embedded newlines) add \n to your pattern. You will need to match the whole set of leading spaces at once, and then in the replacement check the length of what was matched to figure out how many nbsps to insert.

var paragraph is giving me "unterminated string constant" error

I have this file
var paragraph = "Abandon| give up or over| yield| surrender| leave| cede| let go| deliver| turn over| relinquish| depart from| leave| desert| quit| go away from| desert| forsake| jilt| walk out on | give up| renounce| discontinue| forgo| drop| desist| abstain from|
recklessness| intemperance| wantonness| lack of restraint| unrestraint|
abandoned |left alone| forlorn| forsaken| deserted| neglected| rejected| shunned| cast off | jilted| dropped| ";
with a lot of spacing, so it's giving me that error at the spacings.
then running a loop and alerting the output
var sentences = paragraph.split("|");
var newparagraph = "";
for (i = 0; i < sentences.length; i++) {
var words = sentences[i].split(" ");
if (words.length < 4) {
newparagraph += sentences[i] + "|";
}
}
alert(newparagraph);
how do I read from a file that doesn't get errors from spacing?
As the other answers noted, javascript automatically puts a semicolon at the end of (or what it thinks is) every statement. More about it here.
http://en.wikipedia.org/wiki/JavaScript_syntax#Whitespace_and_semicolons
It doesn't understand text with line-breaks in them. You could use the '\' character to signify your text contains line-breaks.
var text = "this is\
a very long\
sentence";
But the above practice is generally frowned upon. Best bet, define strings in one line or use concatenation (+) to break your strings into multiple lines. If your text must contain line-breaks, use '\n' character.
I can't see a quote character at the end of var paragraph = "... line.
You're missing a terminating quote and semi-colon at the end of the var paragraph assignment. You can use a tool like jslint (http://www.jslint.com/) to check your syntax, if in doubt.

Categories

Resources