Regular expressions help in javascript? - javascript

i am not sure as to why this code is not working, on the website where i found the code it say it should print any letter between capital a to z. i tried the same thing with a number, to print numbers between 0-9 but it does not work.
<!DOCTYPE html>
<html>
<body>
<script>
var string = "THIS IS AN EXAMPLE";
var str = /[A-Z]/;
document.write(string.match(str));
</script>
</body>
</html>

EDIT:
updated after clarified question
<script>
var string = "1 2 3 4 8 9 11 15 18 293";
var str = /[0-9]*/g;
var arr = string.match(str);
var length = arr.length;
for (var i = 0; i < length; i++) {
if ( parseInt(arr[i]) <= 9 && parseInt(arr[i]) >= 1){
document.write(arr[i] + " ");
}
}
</script>
new fiddle here
what you are telling javascript to do is only print the first character in the array of results matching your regex. you also have not accounted for the "space" character in your regular expression
to the best of my understanding this is what you are trying to accomplish - but if this is incorrect please clarify what results you are trying to achieve.
take a look at this fiddle
<script>
var string = "THIS IS AN EXAMPLE";
var str = /[A-Z ]*/;
document.write(string.match(str));
</script>
note how ive used /[A-Z ]*/
including the space character in the matching set as well as an asterisk to denote matching any number of these characters. if you are attempting to only match the first word and stop at a space simply remove it.
in either case
here is a great article from the mozilla developer network explaining regex in all of its glory - pertaining specifically to its use with javascript
in case you decide you would like to take a gander at the 'manual'

Related

Create a text area and analyze button

I am working on my college homework. I am having a lot of difficulty with it and getting stuck. My class mates are not helping me and the instructor hasn't responded. I am hoping I might get some help/understanding here. The current assignment I am working on and it is due today is:
Create a page containing a textarea and an “analyze” button. The results area will display the frequency of words of x characters. For example, the text “one two three” contains 2 3-character words and 1 5-character word. An improvement to the original design would be to strip out any extraneous characters that may skew the count.
I am just starting it now, so I will add the code here as I update. I know I won't have a problem with the HTML part, the JavaScript will be my problem. From what I get, I will need to have a function that counts the words and the characters in each word. But it needs to exclude spaces and characters like: ,.';/. I have not run across this code before, so any input on how I should frame the javascript will be helpful. Also it seems he wants me to list how many words have the same characters? am I reading this right?
My code thus far:
<!DOCTYPE html>
<html>
<body>
<textarea id="txtarea">
</textarea>
<input type="button" id="analyze" value="Analyze" onclick="myFunction()" />
<p id="demo"></p>
<p id="wcnt"></p>
<script>
function myFunction() {
var str = document.getElementById("txtarea").value;
var res = str.split(/[\s\/\.;,\-0-9]/);
var n = str.length;
document.getElementById("demo").innerHTML = "There are " + n + " characters in the text area.";
for (var i = 0; i < res.length; i++) {
s = document.getElementById("txtarea").value;
s = s.replace(/(^\s*)|(\s*$)/gi, "");
s = s.replace(/[ ]{2,}/gi, " ");
s = s.replace(/\n /, "\n");
document.getElementById("wcnt").innerHTML = "There are " + s.split(' ').length + " words in the text area.";
}
}
</script>
</body>
</html>
Now I need to figure out how to make it count the characters of each word then output how many words have x amount of characters. Such as 5 words have 4 characters and so on. Any suggestions?
var textarea = document.getElementById("textarea"),
result = {}; // object Literal to hold "word":NumberOfOccurrences
function analyzeFrequency() {
// Match/extract words (accounting for apostrophes)
var words = textarea.value.match(/[\w']+/g); // Array of words
// Loop words Array
for(var i=0; i<words.length; i++) {
var word = words[i];
// Increment if exists OR assign value of 1
result[word] = ++result[word] || 1;
}
console.log( result );
}
analyzeFrequency(); // TODO: Do this on some button click
<textarea id="textarea">
I am working on my college-homework.
Homework I am having a lot of difficulty with it and getting stuck.
My class mates are not helping me and the instructor hasn't responded.
I am hoping I might get some help/understanding here.
</textarea>
Notice how Homework and homework (lowercase) are registered as two different words, I'll leave it to you to fix that - if necessary and implement the analyzeFrequency() trigger on some button click.
Most likely you will have to use JavaScript's split function with regex to define all the characters you do not want to include. Then loop through the resulting array and count the characters in each word.
var words = document.getElementById("words");
var analyze = document.getElementById("analyze");
analyze.addEventListener("click", function(e) {
var str = words.value;
var res = str.split(/[\s\/\.;,\-0-9]/);
for(var i = 0; i < res.length; i++) {
alert(res[i].length);
}
});
<textarea id="words">This is a test of this word counter thing.</textarea>
<br/>
<button id="analyze">
Analyze
</button>
Your instructor does NOT want you to list how may words have the same characters but rather the same number of characters. The basic algorithm:
Assign the value of the text area to a variable.
Convert that string value into an array. In javascript this could be accomplished with the String split method using a regular expression containing a character class.
Iterate over that array examining each element for its length. For each element, increment a counting object's property whose property name is the length of the element.
Iterate over the counting object's property list. Output to the result area each property name and its value.

Replace string with condition in google script

in google script I am trying to replace a %string basing on the character following it.
I've tried using:
var indexOfPercent = newString.indexOf("%");
and then check the character of indexOfPercent+1, but indexOf returns only the first occurrence of '%'.
How can I get all occurrences? Maybe there is easier way to do that (regular expressions)?
EDIT:
Finally I want to replace all my % occurrences to %%, but not if percent sign was part of %# or %#.
To sum up: my string: Test%# Test2%s Test3%. should look like: Test%# Test2%s Test3%%.
I've tried using something like this:
//?!n Matches any string that is not followed by a specific string n
//(x|y) Find any of the alternatives specified
var newString = newString.replace(\%?![s]|\%?![%], "%%")
but it didn't find any strings. I am not familiar with regex's, so maybe it is a simple mistake.
Thanks
Try this code:
// replace all '%'
var StrPercent = '%100%ffff%';
var StrNoPersent = StrPercent.replace(/\%/g,'');
Logger.log(StrNoPersent); // 100ffff
Look for more info here
Edit
In your case you need RegEx with the character not followed by group of characters. Similiar question was asked here:
Regular expressions - how to match the character '<' not followed by ('a' or 'em' or 'strong')?
Thy this code:
function RegexNotFollowedBy() {
var sample = ['Test%#',
'Test2%s',
'Test3%',
'%Test4%'];
var RegEx = /%(?!s|#)/g;
var Replace = "%%";
var str, newStr;
for (var i = 0; i < sample.length; i++) {
str = sample[i];
newStr = str.replace(RegEx, Replace);
Logger.log(newStr);
}
}
I'll explain expression /%(?!s|#)/g:
% -- look '%'
(text1|text2|text3...|textN) -- not followed by text1, 2 etc.
g -- look for any accurance of searched text

Jquery check if special char exists in text value

i need to check if a textarea contains some special characters, so i need to count them 2 (SMS lenght).
I wrote this piece of code but seems that it doesn't find no special chars, also if write only "€€€"
Could you please help me? Also if you would to rewrite directly function, without problem. Thank tou!
var SPECIAL_CHARS = Array('€', '%');
function charUsed() {
var count = $('#text').val().length;
var chars = $('#text').val().split("");
var numberOfSpecialChars = 0;
if ($.inArray(chars, SPECIAL_CHARS) > -1) {
numberOfSpecialChars++;
}
return count + numberOfSpecialChars;
} // function
A rewrite :
var nbSpecialChars = $('#text').val().split(/[€%]/).length - 1;
The idea is to make an array of strings, using your special characters as separator :
'some € chars %' => ["some ", " chars ", ""]
and then use the length of this array to deduce the count of those chars. There are many other (faster) solutions but this one is short.
http://jsfiddle.net/KSm7J/
var chars = $('#text').val().match(/[€%]/g).length;
alert(chars);

Count the number of occurence of a case sensitive word in a paragraph in jquery

I want to count the number of occurrence of a specific words in a paragraph.
I am writing my code for key down event. I may have few hundreds words initially that may increase later on.
SO when the user is typing i will match the words in a paragraph and then get the number of occurrence. I also need to make sure that the match will be case sensitive.
Right now i am using this code:
$('.msg').val().split("AP").length - 1
Where AP is the keyword to match.
But i am not very happy with this.
Actually i have a list of few hundred keywords, how can i implement it efficiently.
Please note the words to match have spaces on both side i.e they are boundary words
Any help is appreciated
You can try something like the following:
var wordList = ["some", "word", "or", "other", "CASE", "Sensitive", "is", "required"],
wordCount = [];
for (var i=0; i < wordList.length; i++)
wordCount[i] = 0;
$("#someField").keyup(function(){
var i,
text = this.value,
re;
for (i = 0; i < wordList.length; i++) {
re = new RegExp("\\b" + wordList[i] + "\\b", "g");
wordCount[i] = 0;
while (re.test(text)) wordCount[i]++;
}
});
Demo: http://jsfiddle.net/zMdYg/2/ (updated with longer word list)
I don't really know what you want to do with the results, so I've just stuck them in a simple array, but you can see in the demo I then output them to the page so you can see it working. Obviously you'd substitute your own requirement in that part.
This is using a regex to test each word. You'll notice that with .split() or .indexOf() you'll get partial matches, e.g., if you look for "other" it will also match partway through "bother" (and so forth), but with the regex I've used \b to test on word boundaries.
For a large list of words you might want to create all the regexes in advance rather than redoing them on the fly in the loop, but it seemed to work fine for my simple test so I thought I wouldn't start doing premature optimisations. I'll leave that as an exercise for the reader...
If split() is not case-sensitive, then I would look at using indexOf(), which is case sensitive.
So maybe something like:
var words_array = ['one', 'two', 'three'];
var carot = 0;
var n_occurences = 0;
$.each(words_array, function(index, value){
while(carot < $('.msg').val().length && carot > -1){
carot = $('.msg').val().indexOf(' ' + words_array[index] + ' ', carot);
if (carot > -1){
n_occurences++;
}
}
});
I haven't tested this but I hope you get the idea.

How do I count the number of words in a string that have 3,4,5 or 6 characters in Javascript?

I have been given a task...
"count the number of words in the string "tx_val" that have 3,4,5 or 6 characters
show these four counts on a single line separated by commas"
I have been trying multiple different loop statements but I cannot seem to get the right answer.
Here is the code I was given to work with :
<html>
<head>
<script language="javascript">
<!--
function fred()
{
var tx_val=document.alice.tx.value;
len_tx=tx_val.length
-->
</script>
</head>
<body>
<form name="alice">
<b>Assignment #1 Javascript</b>
<p>
The text box below is named "tx". The form is named "alice".
<p>
<input type="text" name="tx" formname="alice" size="50" value="the quick brown fox jumped over the lazy dogs back">
</form>
The regular expression /\b\w{3,6}\b/ matches a "word" of 3 through 6 characters in length. Now that definition of "word" may or may not suit your purposes, but it's probably close.
With that, you could do something like:
var matches = theString.match(/\b\w{3,6}\b/g).length;
to get the count.
The escape "\w" matches any "word" character, which to JavaScript means alphanumerics and underscore. If you don't like that, you could construct your own character class. For example, if you only care about words made up of letters, you could do:
var matches = theString.match(/\b[a-zA-Z]{3,6}\b/g).length;
The "\b" escape is a zero-length match for a word delineation. It matches either the start or the end of a word, without itself "consuming" any characters while doing so.
edit — sorry I had originally mistyped a "." in the {3,6} qualifier (and I almost did it again just now :-) — should have been commas.
You can first split the words into an array using the split method. Then you can loop over that array using its forEach method and counting the length of each word.
Here are some simple questions that might help you build up a straightforward approach:
What's a 'word'? How can you find all of them?
Can you put those words into an array of strings?
Can you loop through an array?
Can you increment a counter when looping?
Can you tell me how many letters are in a specific word?
Can you conditionally increment a counter based on an if statement?
Can you nest two loops?
That said, here's how I personally would do it (which probably would not satisfy your homework requirements if you copy/pasted it without understanding it):
var text = "Oh HAI, is this the longest text allowd?"
for (var counts=[],l=3;l<=6;++l){
var re = new RegExp('\\b\\w{'+l+'}\\b','g');
var words = text.match(re);
counts.push(words ? words.length : 0);
}
console.log(counts.join(','));
//-> 2,2,0,1
I don't know Javascript. But your code should go like this:
function fred()
{
var threeCharacterLong = 0;
var fourCharacterLong = 0;
var fiveCharacterLong = 0;
var sixCharacterLong = 0
var tx_val=document.alice.tx.value;
var splittedArray = tx_val.Split(" ");
foreach (var word in splittedArray)
{
if (word.length == 3)
threeCharacterLong++;
else if (word.length == 4)
fourCharacterLong ++;
else if (word.length == 5)
fiveCharacterLong ++;
else if (word.length == 6)
sixCharacterLong ++;
}
}

Categories

Resources