How to count empty lines inside a string in javascript - javascript

I'm trying to count all the empty lines inside a string. My current function kind of works:
function count_empty(text) {
var regex = /\r\n?|\n/g;
var lines = text.split(regex);
var sep = [];
$.each(lines, function(k, val) {
if(!val) {
//sentence
sep.push(val);
}
});
return sep.length;
}
...but I really think it could be achieved with a far better approach with something like this:
function count_empty(text) {
return (text.match(/\r\n?|\n/g) || []).length;
}
Of course, the regex in the 2nd alternative should be retouched to actually accomplish the requirements. So, the question is: What regex should I use in the second approach to retrieve the blank lines only?
One consideration: If a line contains whitespaces only, it will be treated as an empty line.
This textarea's string should return 3 with the function.
<textarea id="test">first line
third line
</textarea>
Thanks!

If you enable multi-line mode, m, for your regular expressions, you can match empty lines, ^$, and count how many matches have been found. Note that [ \t]* will match zero or more spaces or tabs.
function count_lines(text){
return text ? (text.match(/^[ \t]*$/gm) || []).length : 0;
}
This should be really fast since no post-processing after the regular expression is necessary.
See Regex101 for a demo with annotations.

What about this?
function count_empty(text) {
return (text.match(/(^[ \t]*(\n|$))/gm) || []).length;
}
Fiddle

You can just do this
function count_lines(txt){
return (txt.match(/\n(?=\n/g)) || []).length;
}
What the above does is matches \n which is followed by another \n, and then returning the length of matches.
DEMO

Related

Using RegExp, count sentences in a paragraph based on periods, question marks, and exclamation points

So far, I have:
function countSentences(paragraph) {
var regex = new RegExp(`^(?=.*[.?!])[.?!]$`, 'gi');
count = 0;
while (regex.exec(paragraph)) {
count++
}
return count;
}
Whenever I type in a paragraph in the function, it just returns 0.
Just write your regex like this
function count(str){
return ( str.match( RegExp(`[.?!]`, 'gi') ) || [] ).length;
}
console.log(count("This is good. But is it? you decide!"));
For a start you don't really need the RegExp constructor as you're not building a dynamic pattern, so we can use a RegExp literal.
Secondly, you're complicating it. You simply need to look for instances of the relevant punctuation symbols - no need for look-aheads or the like.
function count(paragraph) {
return (paragraph.match(/[.?!]{1,}/g) || []).length;
}
Note, this also guards against sentences that end with overly expressive punctuation patterns like ??? or !?.

Add quotes to all words exluding ()

I have such a sentence:
(CAR AND BUS) OR TRAM
I need to add quotes to all words except AND(it can be OR instead of AND):
So I created such a code for that:
word.replace(/"/g, '').split(" ").map(e => ["AND", "OR"].includes(e) ? e : '"' + e + '"').join(" ");
but as an output, I have an incorrectly formatted query like
"(CAR" AND "BUS)" OR "TRAM"
I do need not to include quotes to the () so as an output I expect to have
("CAR" AND "BUS") OR "TRAM"
How can I achieve such a result?
"(CAR AND BUS) OR TRAM".replace(/([a-zA-Z]+)/gi, function(word){
if(["AND", "OR"].indexOf(word) < 0) return `"${word}"`;
else return word
})
There are plenty of approaches to solve your task. Here is one that is more procedural and it does not use regular expressions.
Basically your task is to split the sentence into words, then process each word, checking if it requires processing and then apply your given ruleset.
Ofcourse this can be written more concise by using regular expression (see other answers) but especially if you have people around in your team that are not so versatile sometimes an more expressive approach is good too.
var sentence = "(CAR AND BUS) OR TRAM"; // Input data
var words = sentence.split(" "); // Get each word of the input
var exclude = ["AND", "OR"]; // Words that should be ignored when processing
var result = []; // result goes here
words.forEach(word=>{ // loop over each word
if(exclude.includes(word)){ // exclude from further processing?
result.push(word); //yes: put into result
} else{ //no: remove ( and ) and enclose with quoationsmark then put into result
result.push("\""+word.replace("(","").replace(")","")+"\"");
}
}
);
console.log(result.join(" "));
Using replace()
Demo: https://regex101.com/r/1kC6zT/2
console.log("(CAR AND BUS) OR TRAM".replace(/(?!AND|OR)(\b[^\s]+\b)/g, '"$1"'))

Detect repeating letter in an string in Javascript

code for detecting repeating letter in a string.
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z])\1+$/).test(str)
alert("repeating string "+hasDuplicates);
I am getting "false" as output for the above string "paraven4sr". But this code works correctly for the strings like "paraaven4sr". i mean if the character repeated consecutively, code gives output as "TRUE". how to rewrite this code so that i ll get output as "TRUE" when the character repeats in a string
JSFIDDLE
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)
alert("repeating string "+hasDuplicates);
The regular expression /([a-zA-Z])\1+$/ is looking for:
([a-zA-Z]]) - A letter which it captures in the first group; then
\1+ - immediately following it one or more copies of that letter; then
$ - the end of the string.
Changing it to /([a-zA-Z]).*?\1/ instead searches for:
([a-zA-Z]) - A letter which it captures in the first group; then
.*? - zero or more characters (the ? denotes as few as possible); until
\1 - it finds a repeat of the first matched character.
If you have a requirement that the second match must be at the end-of-the-string then you can add $ to the end of the regular expression but from your text description of what you wanted then this did not seem to be necessary.
Try this:
var str = "paraven4sr";
function checkDuplicate(str){
for(var i = 0; i < str.length; i++){
var re = new RegExp("[^"+ str[i] +"]","g");
if(str.replace(re, "").length >= 2){
return true;
}
}
return false;
}
alert(checkDuplicate(str));
Here is jsfiddle
To just test duplicate alphanumeric character (including underscore _):
console.log(/(\w)\1+/.test('aab'));
Something like this?
String.prototype.count=function(s1) {
return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
"aab".count("a") > 1
EDIT: Sorry, just read that you are not searching for a function to find whether a letter is found more than once but to find whether a letter is a duplicate. Anyway, I leave this function here, maybe it can help. Sorry ;)

Javascript Match on parentheses inside the string

How do I do a .match on a string that has parentheses in the string?
String1.match("How do I match this (MATCH ME)");
None of the answers are getting me what I want. I'm probably just doing it wrong. I tried to make my question basic and I think doing that asked my question wrong. This is the statement I am tring to fix:
$('[id$=txtEntry3]').focus(function () {
if (!DropdownList.toString().match($('[id$=txtEntry2]').val()) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
ErrorMessageIn("The Ingredient number you entered is not valid.");
return;
}
ErrorMessageOut();
});
This works correctly the problem I am running into is when it tries to match a entry from "txtEntry2" that has "()" in it.
Well it's kinda broken but it works for what I need it to do. This is what I did to fix my problem:
$('[id$=txtEntry3]').focus(function () {
if (!StripParentheses(DropdownList).match(StripParentheses($('[id$=txtEntry2]').val())) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
if (!$('[id$=txtEntry2]').val() == "") {
ErrorMessageIn("The Ingredient number you entered is not valid.");
}
return;
}
ErrorMessageOut();
});
function StripParentheses(String){
x = String.toString().replace(/\(/g, '');
x = x.toString().replace(/\)/g, '');
return x;
}
to get all occurences in e.g. ".. (match me) .. (match me too) .." add the g regexp flag
string.match(/\((.*?)\)/g)
this as also an advantage, that you get only list of all occurences. without this flag, the result will include a whole regexp pattern match (as the first item of resulting array)
If you are interested in the part of the string between parenthesis, then you can use /\(([^\)]*)\)/; if you just need to get the full string, then you can you can use /\([^\)]*\)/.
var str = "How do I match this (MATCH ME)";
str.match(/\((.*?)\)/);

How to extract a string using JavaScript Regex?

I'm trying to extract a substring from a file with JavaScript Regex. Here is a slice from the file :
DATE:20091201T220000
SUMMARY:Dad's birthday
the field I want to extract is "Summary". Here is the approach:
extractSummary : function(iCalContent) {
/*
input : iCal file content
return : Event summary
*/
var arr = iCalContent.match(/^SUMMARY\:(.)*$/g);
return(arr);
}
function extractSummary(iCalContent) {
var rx = /\nSUMMARY:(.*)\n/g;
var arr = rx.exec(iCalContent);
return arr[1];
}
You need these changes:
Put the * inside the parenthesis as
suggested above. Otherwise your matching
group will contain only one
character.
Get rid of the ^ and $. With the global option they match on start and end of the full string, rather than on start and end of lines. Match on explicit newlines instead.
I suppose you want the matching group (what's
inside the parenthesis) rather than
the full array? arr[0] is
the full match ("\nSUMMARY:...") and
the next indexes contain the group
matches.
String.match(regexp) is
supposed to return an array with the
matches. In my browser it doesn't (Safari on Mac returns only the full
match, not the groups), but
Regexp.exec(string) works.
You need to use the m flag:
multiline; treat beginning and end characters (^ and $) as working
over multiple lines (i.e., match the beginning or end of each line
(delimited by \n or \r), not only the very beginning or end of the
whole input string)
Also put the * in the right place:
"DATE:20091201T220000\r\nSUMMARY:Dad's birthday".match(/^SUMMARY\:(.*)$/gm);
//------------------------------------------------------------------^ ^
//-----------------------------------------------------------------------|
Your regular expression most likely wants to be
/\nSUMMARY:(.*)$/g
A helpful little trick I like to use is to default assign on match with an array.
var arr = iCalContent.match(/\nSUMMARY:(.*)$/g) || [""]; //could also use null for empty value
return arr[0];
This way you don't get annoying type errors when you go to use arr
This code works:
let str = "governance[string_i_want]";
let res = str.match(/[^governance\[](.*)[^\]]/g);
console.log(res);
res will equal "string_i_want". However, in this example res is still an array, so do not treat res like a string.
By grouping the characters I do not want, using [^string], and matching on what is between the brackets, the code extracts the string I want!
You can try it out here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match_regexp
Good luck.
(.*) instead of (.)* would be a start. The latter will only capture the last character on the line.
Also, no need to escape the :.
You should use this :
var arr = iCalContent.match(/^SUMMARY\:(.)*$/g);
return(arr[0]);
this is how you can parse iCal files with javascript
function calParse(str) {
function parse() {
var obj = {};
while(str.length) {
var p = str.shift().split(":");
var k = p.shift(), p = p.join();
switch(k) {
case "BEGIN":
obj[p] = parse();
break;
case "END":
return obj;
default:
obj[k] = p;
}
}
return obj;
}
str = str.replace(/\n /g, " ").split("\n");
return parse().VCALENDAR;
}
example =
'BEGIN:VCALENDAR\n'+
'VERSION:2.0\n'+
'PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n'+
'BEGIN:VEVENT\n'+
'DTSTART:19970714T170000Z\n'+
'DTEND:19970715T035959Z\n'+
'SUMMARY:Bastille Day Party\n'+
'END:VEVENT\n'+
'END:VCALENDAR\n'
cal = calParse(example);
alert(cal.VEVENT.SUMMARY);

Categories

Resources