How to make character count with Javascript - javascript

How to correctly make a character count with JS.
My code seems is incorrect, what i'm doign wrong?
<p class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
var str = document.getElementsByClassName('text');
var res = str.innerHTML = str.value.length;
console.log(res);

This can work for you
var x = document.getElementById("text").innerHTML
var str = x.length;
alert("length is:" +str);
console.log(str);
<p id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>

If you look at this definition of the function it returns an array. So you either want the length of the array str.length or to iterate through the array.

getElementsByClassName() returns an array-like collection of elements. Iterate over it and fetch the value:
var str = document.getElementsByClassName('text');
[].forEach.call(str, function(el){
var res = el.value.length;
el.innerHTML = res;
console.log(res);
});

I guess you want to get the length of the content of an element. For that you should be using id selector, not class selector, there can be many elements with the same class but not with the same id. So you should give it some id like: <p id='some_id' class='text'>
Now you can get it through:
document.getElementById("some_id").innerHTML.length
To avoid any leading or trailing spaces, and to get exact length of text, you can try this:
document.getElementById("some_id").innerHTML.trim().length

Related

Compare two strings and return different stretch

I have two strings like these:
var str1 = "lorem ipsum dolor sit amet";
var str2 = "ipsum dolor";
And I'm trying to compare them and get, as result, an array with everything that doesn't match this comparation and the match! One for the beggining and the other one for the ending.
E.g: In this case above, the return should be an array like this:
result[0] //should keep the begining **"lorem "** (with the blank space after word)
result[1] // should keep the ending **" sit amet"** (with the blank space before word)
result[2] // should keep the match **"ipsum dolor"**
All I got was an elegant solution posted by #Mateja Petrovic. But I can get this values separately.
Just like this:
const A = "ipsum dolor"
const B = "lorem ipsum dolor sit amet"
const diff = (diffMe, diffBy) => diffMe.split(diffBy).join('')
const C = diff(B, A)
console.log(C) // jumps over the lazy dog.
I'm really stuck! Any idea?
Thanks a lot!
const diff = (str, query) => [...str.split(query), query];
/*
1. we split the string into an array whenever query is found
2. we spread (...) the array into a new array
3. we add the query at the end of the new array
*/
var str = "lorem ipsum dolor sit amet";
var query = "ipsum dolor";
const result = diff(str, query)
console.log(result)
console.log(result[0])
console.log(result[1])
console.log(result[2])
I don't think what you are asking is logically possible. a "string" can be a single letter, which is going to get very messy. at best maybe something like this?
var str1 = "lorem ipsum dolor sit amet";
var str2 = "ipsum dolor";
var parts = str1.split(str2);
console.log(parts); // ['lorem ', ' sit amet']
You could split the target string by the search string, and append the latter to the solution.
const haystack = 'lorem ipsum dolor sit amet';
const needle = 'ipsum dolor';
const diff = (needle, haystack) =>
[...haystack.split(needle), needle]
console.log(diff(needle,haystack));
// ["lorem ", " sit amet", "ipsum dolor"]

Is there a Regex expression to match every that is not in quotations

I'm working on a Regular Expression that looks at everything except information in quotations. An example would be:
Lorem ipsum "dolor" sit amet, "consectetur" adipiscing elit.
Would change to
Lorem ipsum sit amet, adipiscing elit
I've already tried
.*(?=".*").*
and
`[^"].*[^"]
neither worked so I'd appreciate help.
Heres a way ...
var str = `Lorem ipsum "dolor" sit amet, "consectetur" adipiscing elit.`
console.log(str.replace(/\"[a-z]{1,}\"/g, ''))
I would do something in the line of this. It handles the case where the sentence starts or ends with a quotation mark.
var str = '"Lorem" ipsum "dolor" sit amet, "consectetur", adipiscing "elit."';
var regExp = /(?:^|\W)(\".+?\")(?:\W|$)/g;
var res = str.replace(regExp, " ").trim();
console.log(res);
RegExp explained:
(?:^|\W) - non capturing group of either start of the string or just a space (technically a "non word character" - could be a punctuation, a bracket, etc)
(\".+?\") - anything between " (including the quotation marks themselves)
(?:\W|$) - same as the first one, but checking for the end of a string instead
g flag - check for all occurrences of a matching pattern
Try this , non-greedy (".*?") match two quotations and as few as possible between them.
var a ='Lorem ipsum "dolor" sit amet, "consectetur" adipiscing elit.';
console.log(a.replace(/".*?"/g,''));
I hope to help you :
/[,\w]+(?![^" ]*")/g
var str = 'Lorem ipsum "dolor" sit amet, "consectetur" adipiscing elit.' ;
var res = '' ;
var patt = /[,\w]+(?![^" ]*")/g ;
while ( (arr = patt.exec(str)) != null) { res += arr[0] + ' ' ; }
console.log( res ) ;

Regexp to match words two by two (or n by n)

I'm looking for a regexp which is able to match words n by n. Let's say n := 2, it would yield:
Lorem ipsum dolor sit amet, consectetur adipiscing elit
Lorem ipsum, ipsum dolor, dolor sit, sit amet (notice the comma here), consectetur adipiscing, adipiscing elit.
I have tried using \b for word boundaries to no avail. I am really lost trying to find a regex capable of giving me n words... /\b(\w+)\b(\w+)\b/i can't cut it, and even tried multiple combinations.
Regular expressions are not really what you need here, other than to split the input into words. The problem is that this problem involves matching overlapping substrings, which regexp is not very good at, especially the JavaScript flavor. Instead, simply break the input into words, and a quick piece of JavaScript will generate the "n-grams" (which is the correct term for your n-word groups).
const input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
// From an array of words, generate n-grams.
function ngrams(words, n) {
const results = [];
for (let i = 0; i < words.length - n + 1; i++)
results.push(words.slice(i, i + n));
return results;
}
console.log(ngrams(input.match(/\w+./g), 2));
A word boundary \b does not consume any characters, it is a zero-width assertion, and only asserts the position between a word and non-word chars, and between start of string and a word char and between a word char and end of string.
You need to use \s+ to consume whitespaces between words, and use capturing inside a positive lookahead technique to get overlapping matches:
var n = 2;
var s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
var re = new RegExp("(?=(\\b\\w+(?:\\s+\\w+){" + (n-1) + "}\\b))", "g");
var res = [], m;
while ((m=re.exec(s)) !== null) { // Iterating through matches
if (m.index === re.lastIndex) { // This is necessary to avoid
re.lastIndex++; // infinite loops with
} // zero-width matches
res.push(m[1]); // Collecting the results (group 1 values)
}
console.log(res);
The final pattern will be built dynamically since you need to pass a variable to the regex, thus you need a RegExp constructor notation. It will look like
/(?=(\b\w+(?:\s+\w+){1}\b))/g
And it will find all locations in the string that are followed with the following sequence:
\b - a word boundary
\w+ - 1 or more word chars
(?:\s+\w+){n} - n sequences of:
\s+ - 1 or more whitespaces
\w+ - 1 or more word chars
\b - a trailing word boundary
Not a pure regex solution, but it works and is easy to read and understand:
let input = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
let matches = input.match(/(\w+,? \w+)/g)
.map(str => str.replace(',', ''));
console.log(matches) // ['Lorem ipsum', 'dolor sit', 'amet consectetur', 'adipiscing elit']
Warning: Does not check for no matches (match() returns null)

Split content in last parantheses

In javascript, how can I split string to get content of last parantheses so
var str = "Lorem ipsum (I don't want this data) lorem ipsum (I want this data)";
becames array
["Lorem ipsum (I don't want this data) lorem ipsum "],["I want this data"]
You can use a regular expression and match :
var arr = str.match(/^(.*)\(([^\)]+)\)$/).slice(1);
This produces exactly
["Lorem ipsum (I don't want this data) lorem ipsum ", "I want this data"]
Online explanation of the regex
I always prefer approaches without regex, mainly for performance. It may not be pretty, but it works nontheless!
var str = "Lorem ipsum (I don't want this data) lorem ipsum (I want this data)";
var s = str.lastIndexOf('(');
var e = str.lastIndexOf(')');
var l = e - s;
var data = [
str.substr(0, s).trim(),
str.substr(s + 1, l - 1).trim()
];
// data = ["Lorem ipsum (I don't want this data) lorem ipsum", "I want this data"]

Remove from String (from Array) in Javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove a word from a string
I have a simple string var mystr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit", and I have an array var lipsums = new Array("dolor","consectetur","elit"); Now, I want a simple function which will remove any same word in the string.
So, in the above example, it should remove the words "dolor", "consectetur", and "elit" and my string mystr should be "Lorem ipsum sit amet, adipiscing"
This script should be in Javascript (no jQuery). Any help would be appreciated.
Loop over the array of words to remove, removing all occurances via split/join:
for (var i = 0; i < lipsums.length; i++) {
mystr = mystr.split(lipsums[i]).join('');
}
http://jsfiddle.net/9Rgzd/
You may also want to clean up your whitespace afterwards, which you can do with a regex:
// Note: don't do this in the loop!
mystr = mystr.replace(/\s{2,}/g, ' ');
http://jsfiddle.net/9Rgzd/1/
Like this:
for(i=0; i<lipsums.length; i++) {
mystr = mystr.replace(new RegExp(lipsums[i],"g"), "");
}
Add this AFTER the loop to remove double white space's:
mystr = mystr.replace(/\s{2,}/g, ' ');

Categories

Resources