Javascript slice method testing issue - javascript

another Javascript newbie question here. Suppose I get an alert if there isn't any space in the input string. but I don't get any alert at all. I got this code block from a book and trying to learn by doing in jsfiddle. Am I missing something here? thank you!
var str = prompt("enter some text");
var numChars = str.length;
for (var i = 0; i < numChars; i++){
if (str.slice(i, i + 2 ) === " ") {
alert("no double spaces");
break;
}
}
http://jsfiddle.net/5ruW2/

If you change the if statement to check for double spaces, with two spaces between the quotes, and change the alert to read "Double Spaces!" it works.
var str = prompt("enter some text");
var numChars = str.length;
for (i = 0; i < numChars; i++) {
if (str.slice(i, i + 2) === " ") {
alert("Double Spaces!");
}
}

Related

Print range using for-loop JavaScript

I need to print a range of numbers in a range using a function and a for-loop.
Again I'm stuck on the return value. I believe my code is sufficient for the task but if you have a better idea I'm all ears.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i < rangeStop; i++) {
text += i + ',';
}
return text;
var result = text;
}
printRange(20, 47);
The 'result' is ought to print the numbers 20,21,22...,46,47 but of course it doesn't...
Any help is appreciated.
Regards, Thomas
There are two things you need to fix - your code doesn't print rangeStop, but it does include a trailing comma.
You can fix the former by changing your loop end condition to use <=, and String.prototype.slice can do the latter.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i <= rangeStop; i++) {
text += i + ',';
}
return text.slice(0, -1);
}
document.write(printRange(20, 47));
function printAllNum(rangeStart, rangeEnd){
for(let i = rangeStart; i <= rangeEnd; i++) {
document.write(i + " ")}
}
printAllNum(1,20);

If statement within a for loop within a for loop - condition isn't being met

var text = [["1","1.","The Wagner diatribe and 'The Twilight of the Idols' were published"],["2","2.","suspect that the delay was due to the influence of the philosopher's"],["3","3.","bounds were marked by crosses. One notes, in her biography of him--a"]];
var amountOfTexts = text.length;
var tempArray = [];
for(var i=0; i<amountOfTexts; i++){
tempArray = [];
var current = text[i][2];
var x = current.length;
for(var j=0; j<x; j++){
var y = j+1;
if(current.substr(j,y) === " "){
tempArray.push("counter");
}
}
console.log(tempArray.length);
var nearlyWords = tempArray.length;
var words = 1+nearlyWords;
text[i].push(words);
}
This prints to console:
0
0
1
Where I'd be expecting:
11
12
12
It's meant to push the word count of the string in text[i][2] to text[i][3].I have checked through it, and the closest thing to the problem is the conditions of the if statement... but they seem fine.
Question: why is it that it won't work?
You are using the substr method wrong, it doesn't take the same parameters as the substring method.
Either use substr and specify the length as the second parameter:
if (current.substr(j, 1) === " ") {
or use substring with your current parameters:
if (current.substring(j, y) === " ") {
You can also use the charAt method to get a character, which seems more natural:
if (current.charAt(j) === " ") {
In newer browsers (IE 8 and later) you can also get characters using bracket syntax:
if (current[j] === " ") {
You can use current.charAt(j) === " " it would be more appropriate, here is code
for(var i=0; i<amountOfTexts; i++){
...
for(var j=0; j<x; j++){
var y = j+1;
if(current.charAt(j) === " "){
tempArray.push("counter");
}
}
...
}

string method exact text

So, I am brand spanking new to JavaScript. I am practicing right now with a Codeacedemy tutorial, and it had me create a program that finds my name in a string of text. But, I realized that if I use a name thats similiar to mine, it will return the other name too. What method can I use or how can I refine the code so that it will only match the exact name in the string?
Here's the code:
/*jshint multistr:true */
var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code";
var myName = "Zachary";
var hits = [];
for (var i = 0; i < text.length; i++){
if (text[i] == 'Z') {
for (var j = i;j < (i + myName.length); j++) {
hits.push(text[j]);
}
}
}
if (hits === 0) {
console.log("Your name was not found!");
}
else {
console.log(hits);
}
You could String.split the string at the white spaces to create an array of words and then check each word against your test string, thus preventing matches within a substring. (with an alternative loop while)
Javascript
var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code",
myName = "Zachary",
hits = 0,
array = text.split(/\s/),
length = array.length,
i = 0;
while (i < length) {
if (myName === array[i]) {
hits += 1;
}
i += 1;
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}
On jsfiddle
Or if you really want to have fun with checking the string by loops then you could do something like this.
Javascript
var text = "Zachary Hello my name is Zachary Sohovich. I'm a 20 year old dude from ZacharySouthern California and I loZacharyve to code Zachary",
textLength = text.length,
myName = "Zachary",
nameLength = myName.length,
check = true,
hits = 0,
i = 0,
j;
while (i < textLength) {
if (check) {
if (i !== 0) {
i += 1;
}
j = 0;
while (j < nameLength) {
if (text.charAt(i + j) !== myName.charAt(j)) {
break;
}
j += 1;
}
if (j === nameLength && (/\s/.test(text.charAt(i + j)) || i + j === textLength)) {
hits += 1;
i += j;
}
}
i += 1;
check = /\s/.test(text.charAt(i));
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}
On jsfiddle
Note: there are a number of other possible solutions that will do the same for you.
**
for(var i = 0; i < text.length ; i++){
if(text[i] === "Z"){
var getText = text.substring(i, i + myName.length);
if(getText === myName)
{
for(var j = i; j < (myName.length + i); j++){
hits.push(text[j]);
}
}
}
}
**
It'll do... easy one.
You need not do all those stuff.
Just find your name with following code
if(text.indexOf(myName) !== -1){
console.log('Found');
}
If its the total number of occurrences you would like to find
var count = text.match(/Zachary/g).length;
console.log(count)
Here's my enhanced version of that lesson.
/*jshint multistr:true */
var text = "Anastasius is known to have had a brother named Flavius Paulus, who served \
asRoman consul in 496. A sister-in-law, known as Magna, was mother to Irene and \
mother-in-law to Olybrius. This Olybrius was son of Anicia Juliana and Areobindus \
Dagalaiphus Areobindus. The daughter of Olybrius and Irene was named Proba. She \
married Probus and was mother to a younger Juliana. This younger Juliana married another \
Anastasius and was mother of Areobindus, Placidia, and a younger Proba. Another nephew \
of Anastasius was Flavius Probus, Roman consul in 502. Caesaria, sister of Anastasius, \
married Secundinus. They were parents to Hypatius and Pompeius. Flavius Anastasius \
Paulus Probus Moschianus Probus Magnus, Roman Consul in 518 also was a great-nephew of \
Anastasius. His daughter Juliana later married Marcellus, a brother of Justin II. The \
extensive family may well have included viable candidates for the throne.";
var textAsWords = text.split(/\s/);
var myName = "Anastasius";
var hits = [];
for (var i = 0; i < textAsWords.length; i++) {
if (myName === textAsWords[i]) {
hits.push(textAsWords[i]);
}
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}
This is what I came up with, staying close to the original exercise.
This consisted of comparing each letter in the text to the first character of the name. On finding that character, you had to add it and any characters that followed into an array, only stopping when the number of characters were equal to the number of letters in the name.
Next, the student was asked to improve the code so it would only add letters matching the exact name. Because the original exercise did not use whitespace or searching for an occurence of the name in one complete string of letters, I did not either.
/*jshint multistr:true */
var text = "olleboleYntke Mchael MichaetMichael S1knol E E rin oef goblinMichael kdmS3ksMichael K elkekeerifdlkùYnyslght MichaelSerind";
myName = "Michael";
var hits = [];
var getCharName = function(namePos) {
charName = myName[namePos];
};
for (i = 0; i <= text.length; i++) {
namePos = 0;
getCharName(namePos);
if (text[i] === charName) {
var letterMatch = false;
for (j = 0; j < myName.length; j++) {
getCharName((namePos + j));
if (text[(i + j)] === charName) {
letterMatch = true;
} else {
letterMatch = false;
}
}
if (letterMatch === true) {
for (j = 0; j < myName.length; j++) {
hits.push(text[(i + j)]);
}
}
}
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}
I'm on the same exercise, and this is my answer.
The method first finds a match with the first letter of myName. When we find a match, we place a X marker on it and run down the text to see if there is a full match. If there is a full match, we return to the X marker and place the correct length of text into the output array "hits". After placing all the letters into the array, we return to the X marker to continue with the rest of the text.
If we don't have a full match, we return to our X spot and continue on to find a match with the first letter of myName again.
var text = "HahahnhahahahnhaHahahahahahahahahahahahaHahahahahahahahahahaHahahahahahnhaHahnhahahahahahahahahaHahaha"
var myName = "Hahn"
var hits =[] //the output will be an array
for(i=0; i<text.length; i++){
var m = 0;
if(text[i] === myName[0]){
for (j=0; j<myName.length; j++){
if (text[i+j] !== myName[m]){
break
}
m++;
if (m === myName.length){
for (n=0; n<myName.length; n++){
hits.push(text[i+n]);
}
}
}
}
}
console.log(hits)
The shortest way of finding your name is to use .match example below:
var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from
Southern California and I love to code";
var nameCheck = text.match(/zachary/gi)
console.log(nameCheck)
Note that THE gi after your name this tells the console to log all matches irrespective of case to use. You can also use .match to also be case sensitive by replacing gi with g.

Dividing words from text starting with a certain character

I want to test each word from a text if it starts with the character # if it does, i will put the word in variable 'response' if not, i will continue searching.
I tried something like :
var found = false;
for (i = 0; i < text.length; i++) {
if (found = /^#...$/.test(text[i])) {
found = true;
}
if (found== true){
//other stuff
}
}
could you help me with this one ?
You can use split on space, and then use substring to find the first letter. Then compare it.
Demo
var arr= text.split(' ');
for (i = 0; i < arr.length; i++) {
if (arr[i].substring(0,1) == '#') {
console.log('found!: ' + arr[i]);
break;
}
}
You probably want something like:
var found = false, response;
for (i = 0; i < text.length; i++) {
if (/^#.*$/.test(text[i])) {
found = true;
response = text[i];
break;
}
}
That matches everything that starts with a #. If you just want to match non-space characters, use the RegEx /^#(\S)*$/

How to multiply a variable?

<script type = "text/javascript">
//Add spaces between menu links
//Placement: Global Header
//Coded by Game
var spaces = "2"; //Edit number of spaces between menu links (1,2 or 3)
var a = document.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].parentNode.parentNode.className == "menubg" && a[i].innerHTML.match(/Home|new topics|help|search|members|calendar|admin|profile|logout|register|login/i)) {
if (spaces == "1") {
a[i].innerHTML += " ";
}
if (spaces == "2") {
a[i].innerHTML += " ";
}
if (spaces == "3") {
a[i].innerHTML += " ";
}
}
}
</script>
The code above is meant to let the useer add spaces between their menu items. It works fine. But how do I make it to where they can add as many spaces as they would like, instead of limiting them to 3? Maybe somehow they would add their number in the var 'spaces' and the code would multiply &nbsp by that numvber?
Just use a loop:
var spaces = 2;
[..]
for(var i = 0; i < spaces; ++ i)
a[i].innerHTML += "&nbsp";
I would generate the string in a separate method, like:
function getSpaces(count) {
var spaces = "";
for(var i = 0; i < count; i++) {
spaces += "&nbsp";
}
return spaces;
}
and then
a[i].innerHTML = getSpaces(2); //etc
This way you set innerHTML and access the array only one time, and also don't have repeated code.
Avoid innerHTML if you can, since it deletes and recreates the entire content of the element. Prefer appendChild and createTextNode instead. For instance:
a[i].appendChild(document.createTextNode(new Array(spaces + 1).join("\u00A0")));
Why don't you just create a loop inside your if clause that adds an every time you go through the loop?

Categories