Let say I have a string = 'all these words are three characters orr longer'
I want to check it
if (string.someWayToCheckAllWordsAre3CharactersOrLonger) {
alert("it's valid!");
}
How can I do that?
Split the string into an array, then check if each word is longer than 3 characters using every.
var string = 'all these words are three characters orr longer';
// Using regex \s+ to split the string, so only words are get in the array
string.trim().split(/\s+/).every(e => e.length >= 3);
You can use every
Before you can use every the string need to be pre-processed.
trim the string, remove the leading and trailing spaces.
split the string by one or more space characters
Then use every to check if length every element of the array is greater than or equal to three.
Demo
var string = 'all these words are three characters orr longer';
string.trim().split(/\s+/).every(function(e) { return e.length >= 3; });
how about something like this
var string = "all these words are three characters orr longer";
var words = string.split(' ');
var allWordsAreLongerThanThreeChars = true;
for(var i=0;i<words.length;i++){
if(words[i].length < 3){
allWordsAreLongerThanThreeChars = false;
return;
}
}
Two simple steps: split string into an array using .split(), loop through the array and check the length of each word using .length(). Hope this helps.
var string = 'all these words are three characters orr longer';
var stringArray = string.split(" ");
for (var i = 0; i < stringArray.length; i++){
if(stringArray[i].length >= 3) {
alert(stringArray[i]);
}
};
Related
I Have the function WordSplit(strArr) which has to read the array of strings stored in strArr, which will contain 2 elements: the first element will be a sequence of characters, and the second element will be a long string of comma-separated words, in alphabetical order, that represents a dictionary of some arbitrary length.
For example: strArr can be: ["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]. My goal is to determine if the first element in the input can be split into two words, where both words exist in the dictionary that is provided in the second input. In this example, the first element can be split into two words: hello and cat because both of those words are in the dictionary.
You can create a Set from the dictionary (after splitting on a comma) and then test every single splitting point, checking if the two words obtained at each point exist in the Set.
function WordSplit([word, dictionary]) {
dictionary = new Set(dictionary.split(","));
for (let i = 0; i < word.length; i++) {
if (dictionary.has(word.slice(0, i)) && dictionary.has(word.slice(i))) {
console.log(word, 'can be split into', word.slice(0, i), 'and', word.slice(i));
return true;
}
}
return false;
}
console.log(WordSplit(["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]));
The only way I can think of doing it is having a String Array of dictionary words. This obviously wouldn't be as comprehensive, and sort of laborious. You could check each word in strArr against each of your words in your String Array of dictionary words using a for loop, and if the word in strArr contains any dictionary word using the contains method, then you could split the word in strArr into two parts: part1 going from charAt 0 in str[i] until the CharSequence s, and part2 going from s to the end of str[i].
for(int i = 0; i < strArr.length; i++) {
for (int x = 0; x < words.length; x++) {
CharSequence s = words[x]
if(strArr[i].contains(s) {
String part1 = strArr[i].split(0,s);
String part2 = strArr[i].split(s);
}
System.out.println(part1 + "" + part2);
}
}
I want to split the string in to different parts. I will have some string which will be generated dynamically which will contains 500 characters. I want to split in to 5 parts. What i mean is i want to take 100 characters in to array[0], next 100 characters in array[1] ....
Example:
var string = "kjfaorj.......................................................";
array[0] = "kjfaorj..... up to 100 characters";
array[1] = " next 100 characters ";
..........................
..........................
if(str.length % 100 == 0) //If the string contains exactly 500 or 400...etc
count = str.length / 100;
else
count = str.length / 100 +1; //If the string contains exactly 505 or 417...etc
for(var i=0;i<count;i++)
array[i] = s.substring(i*100,(i*100)+(100));
Second approach is good for dynamic string
Try this:
var string= "kjfaorj.......................................................";
var array=[];
array[0] = string.substring(0,99);
array[1] = string.substring(100,199);
array[2] = string.substring(200,299);
array[3] = string.substring(300,399);
array[4] = string.substring(400,499);
The following loop will split up any string in pieces of 100 characters. The last element of the array will contain the remaining number of characters (but never more than 100).
If you’re certain your initial string will contain exactly 500 characters, you’ll always get an array of five elements, each one containing 100 characters.
var str = "kjfaorj....................................................... etc.";
for(var arr = [], i = 0; i < str.length - 1; i += 100) {
arr.push(str.substr(i, 100));
}
The difference between substr and substring is that substr expects the length of the substring, whereas substring expects the first and the last index.
As i see "jquery" tag in your question,i want to introduce my powerful JQuery Plugin .
Its String As JQuery
one of features of this plugin is to convert a String to Array : Each n consecutives characters of String is an item in this Array.
Syntax
var myarray=$(myString).toStrArray(eachN);
for you case , you can use it as following ;
var string = "kjfaorj.......................................................";
var myarray=$(string).toStrArray(100);
Demo
http://jsfiddle.net/abdennour/E8LhJ/
Here's a more generic function for any string length:
function splitupString(str,chunklen){
str = str.split('');
var chunks = Array((str.length/chunklen)^0).join(',').split(',');
return chunks
.map(function(){return this.splice(0,chunklen).join('');},str)
.concat(str.join(''));
}
// usage example
var strsplitted = splitupString('123456789012345678901234567890123',5);
//=> [12345,67890,12345,67890,12345,67890,123]
jsFiddle example
If you need to split the string to exactly 100 characters chunks then
var foo = bar.match(/.{100}/g);
If you need to split to chunks having no more than 100 characters, then
var foo = bar.match(/.{1,100}/g);
Basically, like if you were to say
var string = 'he said "Hello World"';
var splitted = string.split(" ");
the splitted array would be:
'he' 'said' '"Hello World"'
basically treating the quotation mark'd portion as a separate item
So how would I do this in javascript? Would I have to have a for loop that goes over the string checking if the scanner is inside a set of quotation marks? Or is there a simpler way?
You could use regular expressions:
var splitted = string.match(/(".*?")|(\S+)/g);
Basically it searches at first for strings with any characters between quotes (including spaces), and then all the remaining words in the string.
For example
var string = '"This is" not a string "without" "quotes in it"';
string.match(/(".*?")|(\S+)/g);
Returns this to the console:
[""This is"", "not", "a", "string", ""without"", ""quotes in it""]
First of all, I think you mean this:
var string = 'he said "Hello World"';
Now that we've got that out of the way, you were partially correct with your idea of a for loop. Here's how I would do it:
// initialize the variables we'll use here
var string = 'he said "Hello World"', splitted = [], quotedString = "", insideQuotes = false;
string = string.split("");
// loop through string in reverse and remove everything inside of quotes
for(var i = string.length; i >= 0; i--) {
// if this character is a quote, then we're inside a quoted section
if(string[i] == '"') {
insideQuotes = true;
}
// if we're inside quotes, add this character to the current quoted string and
// remove it from the total string
if(insideQuotes) {
if(string[i] == '"' && quotedString.length > 0) {
insideQuotes = false;
}
quotedString += string[i];
string.splice(i, 1);
}
// if we've just exited a quoted section, add the quoted string to the array of
// quoted strings and set it to empty again to search for more quoted sections
if(!insideQuotes && quotedString.length > 0) {
splitted.push(quotedString.split("").reverse().join(""));
quotedString = "";
}
}
// rejoin the string and split the remaining string (everything not in quotes) on spaces
string = string.join("");
var remainingSplit = string.split(" ");
// get rid of excess spaces
for(var i = 0; i<remainingSplit.length; i++) {
if(remainingSplit[i].length == " ") {
remainingSplit.splice(i, 1);
}
}
// finally, log our splitted string with everything inside quotes _not_ split
splitted = remainingSplit.concat(splitted);
console.log(splitted);
I'm sure there are more efficient ways, but this produces an output exactly like what you specified. Here's a link to a working version of this in jsFiddle.
I am trying to count the number of words in a given string using the following code:
var t = document.getElementById('MSO_ContentTable').textContent;
if (t == undefined) {
var total = document.getElementById('MSO_ContentTable').innerText;
} else {
var total = document.getElementById('MSO_ContentTable').textContent;
}
countTotal = cword(total);
function cword(w) {
var count = 0;
var words = w.split(" ");
for (i = 0; i < words.length; i++) {
// inner loop -- do the count
if (words[i] != "") {
count += 1;
}
}
return (count);
}
In that code I am getting data from a div tag and sending it to the cword() function for counting. Though the return value is different in IE and Firefox. Is there any change required in the regular expression? One thing that I show that both browser send same string there is a problem inside the cword() function.
[edit 2022, based on comment] Nowadays, one would not extend the native prototype this way. A way to extend the native protype without the danger of naming conflicts is to use the es20xx symbol. Here is an example of a wordcounter using that.
Old answer: you can use split and add a wordcounter to the String prototype:
if (!String.prototype.countWords) {
String.prototype.countWords = function() {
return this.length && this.split(/\s+\b/).length || 0;
};
}
console.log(`'this string has five words'.countWords() => ${
'this string has five words'.countWords()}`);
console.log(`'this string has five words ... and counting'.countWords() => ${
'this string has five words ... and counting'.countWords()}`);
console.log(`''.countWords() => ${''.countWords()}`);
I would prefer a RegEx only solution:
var str = "your long string with many words.";
var wordCount = str.match(/(\w+)/g).length;
alert(wordCount); //6
The regex is
\w+ between one and unlimited word characters
/g greedy - don't stop after the first match
The brackets create a group around every match. So the length of all matched groups should match the word count.
This is the best solution I've found:
function wordCount(str) {
var m = str.match(/[^\s]+/g)
return m ? m.length : 0;
}
This inverts whitespace selection, which is better than \w+ because it only matches the latin alphabet and _ (see http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.2.6)
If you're not careful with whitespace matching you'll count empty strings, strings with leading and trailing whitespace, and all whitespace strings as matches while this solution handles strings like ' ', ' a\t\t!\r\n#$%() d ' correctly (if you define 'correct' as 0 and 4).
You can make a clever use of the replace() method although you are not replacing anything.
var str = "the very long text you have...";
var counter = 0;
// lets loop through the string and count the words
str.replace(/(\b+)/g,function (a) {
// for each word found increase the counter value by 1
counter++;
})
alert(counter);
the regex can be improved to exclude html tags for example
//Count words in a string or what appears as words :-)
function countWordsString(string){
var counter = 1;
// Change multiple spaces for one space
string=string.replace(/[\s]+/gim, ' ');
// Lets loop through the string and count the words
string.replace(/(\s+)/g, function (a) {
// For each word found increase the counter value by 1
counter++;
});
return counter;
}
var numberWords = countWordsString(string);
I would like to limit the substr by words and not chars. I am thinking regular expression and spaces but don't know how to pull it off.
Scenario: Limit a paragraph of words to 200 words using javascript/jQuery.
var $postBody = $postBody.substr(' ',200);
This is great but splits words in half :) Thanks ahead of time!
function trim_words(theString, numWords) {
expString = theString.split(/\s+/,numWords);
theNewString=expString.join(" ");
return theNewString;
}
if you're satisfied with a not-quite accurate solution, you could simply keep a running count on the number of space characters within the text and assume that it is equal to the number of words.
Otherwise, I would use split() on the string with " " as the delimiter and then count the size of the array that split returns.
very quick and dirty
$("#textArea").val().split(/\s/).length
I suppose you need to consider punctuation and other non-word, non-whitespace characters as well. You want 200 words, not counting whitespace and non-letter characters.
var word_count = 0;
var in_word = false;
for (var x=0; x < text.length; x++) {
if ( ... text[x] is a letter) {
if (!in_word) word_count++;
in_word = true;
} else {
in_word = false;
}
if (!in_word && word_count >= 200) ... cut the string at "x" position
}
You should also decide whether you treat digits as a word, and whether you treat single letters as a word.