I am trying to break up this string by first splitting it into sections divided by ';'. Then I want to split those sections divided by ','. It is not working though and I am about to break my computer. Could someone please help me figure this out.
You can play around with my jsfiddle if you want... http://jsfiddle.net/ChaZz/
var myString = "Call 1-877-968-7762 to initiate your leave.,-30,0,through;You are eligible to receive 50% pay.,0,365,through;Your leave will be unpaid.,365,0,After;";
var mySplitResult = myString.split(";");
for(i = 0; i < mySplitResult.length -1; i++){
var mySplitResult2 = i.split(",");
for(z = 0; z < mySplitResult2.length -1; i++) {
//document.write("<br /> Element " + i + " = " + mySplitResult[i]);
document.write("<br/>Element" + z + " = " + mySplitResult[z]);
}
}
i is a number, as that's how you defined it.
To split the string, you need to access the i member of the Array.
var mySplitResult2 = mySplitResult[i].split(",");
If I may, if you have to split with character a then character b, the simplest would be :
string.split('a').join('b').split('b')
Related
<textarea id="check" cols="50" rows="20"></textarea>
<script>
var text = document.getElementById("check").value;
var lengthA = text;
for (var i = 0; i < lengthA.length; i++) {
var space = " ";
if (lengthA[i] === space) {
var next = lengthA[i] + 1;
if (next === space) {
lengthA.replace(lengthA[i], "");
}
}
}
var length3 = lengthA.length - length2;
var words = length3 + 1;
</script>
Alright bois, me got a problemo! Im attempting to make a word counter through the law that each space equals a word (1:1). Im not sure why it is not working, it makes sense to me in my mind. I have attempted several alternatives and dwelled hours upon trying to fix this chunk. Thank you in advance to anyone that answers, even if it doesn't work! :)
EDIT: Regular expressions did the trick and replaced the incorrectly used for loop and if statements. Thanks
How about just the below -
var text = document.getElementById("check").value.replace (/ +/g, " ");
Not sure, why you would need a for loop to begin with.
/ +/ will more than 1 space
g will do all the changes throughout the text
To remove the duplicate space, the following code
lengthA.replace(lengthA[i], "");
should be
lengthA = lengthA.substring(0, i) + lengthA.substring(i + 1);
// i should not increase
i--;
continue;
You misunderstand the usage of replace.
Use str.replace() of JavaScript to do this. This will remove not only space but also work for tabs, newlines etc.
Usage:
var string = string.replace(/\s\s+/g, ' ');
So change below code:
var lengthA = text;
for (var i = 0; i < lengthA.length; i++) {
var space = " ";
if (lengthA[i] === space) {
var next = lengthA[i] + 1;
if (next === space) {
lengthA.replace(lengthA[i], "");
}
}
}
To this:
var lengthA = text.replace(/\s\s+/g, ' ');
Reference here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
I would like to do something like this with JavaScript. This is my code for creating the first half:
<script>
var numberOfLines = 10;
var str = '*';
var space = ' ';
for (var i = 0; i < numberOfLines; i++){
document.write(str + '<br>');
str = str + "*";
}
</script>
How can I finish it?
You can use Array.join to create your repeated characters. Use a monospaced font to preserve the space width.
document.addEventListener("DOMContentLoaded", function(event) {
var output = "";
var numberOfLines = 10;
for (lineNum = 0; lineNum < numberOfLines; lineNum++) {
output += Array(lineNum + 2).join("*") + Array(((numberOfLines * 2) - (2 * (lineNum))) -1).join(" ") + Array(lineNum + 2).join("*") + "<br>";
}
document.getElementById("result").innerHTML = output;
});
#result {font-family: monospace;}
<div id="result"></div>
This is not perfect but very close:
var numberOfLines = 10;
var str = '*';
var arr = [" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "];
var spaces = arr.join("");
for (var i = 0; i < numberOfLines; i++) {
document.write(str + spaces + str + '<br>');
str = str + "*";
arr.splice(-1,1);
arr.splice(-1,1);
spaces = arr.join("");
}
While simple in concept, there's actually a lot to consider when doing this, so lets analyze your code and build from there.
for (var i = 0; i < numberOfLines; i++) {
document.write(str + '<br');
str = str + "*";
}
this will loop through numberOfLines times. It will also output str numberOfLines times. Each loop, you're printing to the document; however, you would like to add a lot of spaces to str as well as a dynamic number of * characters before printing, and each time it will be a different number of spaces. Therefore, you either need to re-build str on each iteration of the loop, or build the entire string str prior to using document.write()
There are many different ways you can accomplish this, I'll go through two:
With a function
You can create a function to build each line. To do this, your function will need to know a few things:
How many lines will there be?
Which line are we currently on?
What character should you use for the visible parts of the triangle?
What character should you use for the invisible parts of the triangle?
So we can start by creating a function, we'll call it generateTriangleLine.
To generate a line, we will want to look at how many of the visible character we want to show, and how many of the invisible. Because there are two sides to this, we will want to output twice as many characters as the current line number:
function generateTriangleLine(visible, invisible, numberOfLines, currentLine) {
// Let's initialize the line so that it has no characters:
var line = '';
// We want to output twice as many characters as there are lines
// So we will loop from 0 to (but not including) numberOfLines * 2
for (var i=0; i<numberOfLines*2; i++) {
if (i<=currentLine || i>=(2*numberOfLines - currentLine - 1)) {
// If we are at the beginning, or the end of the line, we want to output characters.
// We want to add as many visible characters as the line number we are on!
// At the end of the line, 2*numberOfLines = 20. If currentLine starts at 0,
// we will want to draw one visible character, so we need to subtract one from this.
line += visible;
} else {
// If we aren't at the beginning or end, just add the invisible character.
line += invisible;
}
}
// And we want to return the line:
return line;
}
In our code, we can then loop through numberOfLines times, generating each line using our function:
for (var i=0; i<numberOfLines; i++) {
// We'll add a <br> to each line, so that it is drawn appropriately.
document.write(generateTriangleLine('*', ' ', numberOfLines, i) + '<br>');
}
If we run this, we'll get the appropriate output, but it won't necessarily be formatted correctly. This is because most fonts that you read on a daily basis have different widths for each character. The easiest way we can fix this is by wrapping our output in <pre> tags:
document.write('<pre>');
for (var i=0; i<numberOfLines; i++) {
// We'll add a <br> to each line, so that it is drawn appropriately.
document.write(generateTriangleLine('*', ' ', numberOfLines, i) + '<br>');
}
document.write('</pre>');
With a nested for loop to generate the entire output
The other approach we can take is exactly the same as with the function above, but instead of calling a function to generate each line, we generate each line within for loops, and then output everything at the end altogether:
// The first loop will be for each line.
for (var i = 0; i < numberOfLines; i++) {
// The nested for loop will be for each character on each line
// Remember, we have twice as many characters as we do lines
for (var x = 0; x < numberOfLines * 2; x++) {
// Just like we did in the function, we want to check
// if we're at the beginning or the end of the line
// Again, we subtract one from the end so that we still output at least one * on
// the first line.
if (x <= i || x >= (numberOfLines*2) - i - 1) {
// If we are at the beginning or end, output the *
str += "*";
} else {
// Otherwise, output the space
str += space;
}
}
str += '<br>';
}
Once again, we will get the correct output; however, we need to adjust for the letter widths so we can wrap our text in <pre> tags.
Keep in mind, there are numerous ways to solve problems with programming. I've only provided a couple of examples. I would highly encourage you to practice by coming up with your own way of doing this using the skills you learn from the various responses!
so I need to be able to enter a string and have it reversed. I must have one library JS file and one regular JS file. Here is my library JS file:
function reverseString(string) {
var reversedString= "";
for(var i = string.length -; i >=; --i) {
reversedString = reversedString + string[i];
}
return reversedString;
}
and here is my regular one
var stringEntered = prompt("Enter a string:")
var newString = reverseString(stringEntered);
document.write("the reverse of the string \" + stringEntered + \ " is \" + newString + ".")
I entered it the exact same way my professor showed us, and I when I try to run my HTML file (which is coded to call both these files), nothing happens. What am I missing?
There're a lot of syntax issues. Here's a working code:
function reverseString(string) {
var reversedString = "";
// This loop had a lot of basic syntax issues and also
// "i" was starting from the length value, while a string
// is a character array and array indexes start from 0 instead of 1
for (var i = string.length - 1; i >= 0; --i) {
reversedString = reversedString + string[i];
}
return reversedString;
}
var stringEntered = prompt("Enter a string:");
var newString = reverseString(stringEntered);
// Here I found a mess of "/" characters
// I've changed the horrible document.write with alert so you can check the result without opening the debugger...
alert("the reverse of the string " + stringEntered + " is " + newString + ".")
Here is a concise method of reversing a string:
function reverseString(string) {
return string.split('').reverse().join('');
}
var str = prompt("Enter a string", "a racecar dad");
alert(reverseString(str));
Turn it into an array, reverse the array, turn it back into a string.
Edit: Sorry, didn't see #SidneyLiebrand's comment telling you to do the same.
I'm trying to use basic operators to create my own custom array in JavaScript, I guess.
This book I'm reading, "Eloquent JavaScript", has an exercise in Chapter 1 that asks me to make a pyramid using the "print" function. There's no print function in any of my interpreters, and it doesn't say how to make a print function. So, I don't have a print function, and I'm using alerts.
Here's the code.
var line = "";
var counter = 0;
while (counter < 10) {
line = line + "#";
print(line);
counter = counter + 1;
}
So, I was trying to use alerts, instead:
var line = "";
var counter = 0;
while (counter < 10) {
line = line + "#";
alert(line);
counter = counter + 1;
}
But the alert isn't a triangle. It's a bunch of boxes where the number of pound signs grows each time.
I want to create a string concatenation and then print out the entire result.
This is what I came up with:
string = "";
counter = 0;
signs = "#";
while (counter < 10){
string = string + signs + "\n";
signs = signs + "#";
counter = counter + 1;
}
alert(string);
So, I am just wondering, is there a better way to create arrays without knowing how to create array variable?
Your first pound-sign (tip of pyramid) should be spaced half the length of your base of your pyramid. So, if your base is 10 # signs long, then the top of your pyramid should be spaced out to 4 spaces then print the # sign.
Second, to make a true pyramid, you'll need to print top to bottom so your second row is progressively getting larger. Think in odd numbers:
// Example
Tip: 1 char
2nd row: 3 chars
3rd row: 5 chars
4th row: 7 chars
5th row: 9 chars
6th row: 11 chars
etc
Your newline character is wrong. It should be a \n. If printing to HTML, then use <BR>.
Alternatively, you can use console.log to print your characters.
The newline character is "\n" not "/n". (The "escape" character in general is backslash not forward slash.)
Also, you have a typo that you said sings = ... instead of signs = ...
EDIT: OK, so you've updated your question to correct both of those problems. Regarding your new question:
So, I am just wondering, is there a better way to create arrays
without knowing how to create array variable?
It sounds like you don't really understand what an array variable is: an array is a data structure that allows you to store data items that are selected by indices. Why do you think you need an array for this "pyramid" functionality?
As an aside, your code could be improved using += and ++:
a = a + b; can be abbreviated as a += b;
a = a + 1; can be abbreviated as a++;
This should work
var stringBuilder = "";
counter = 0;
signs = "#";
while (counter < 10){
stringBuilder = stringBuilder + signs + "\n";
signs = signs + "#";
counter = counter + 1;
}
alert(stringBuilder);
Newline is backslash and "n"
You need only one newline character that is within the loop
The following code should work:
string = "";
counter = 0;
signs = "#";
while (counter < 10){
string = string + signs + "\n";
signs = signs + "#";
counter = counter + 1;
}
alert(string);
The major differences are as follows:
You can't include the newline character in the string you are building, otherwise newlines from previous iterations will still be included in subsequent iterations.
The newline character is \n and not /n.
string can start off as being empty, since you will be appending a "#" each time.
This would be another way to do it:
<script>
string = ""; height = 10;
for(i = 1; i <= height; i++){
string += Array(i).join('#') + '<br>';
}
document.write(string);
</script>
Output:
#
##
###
####
#####
######
#######
########
#########
Now with some more modification:
<script>
string = ""; height = 10;
for(i = 1; i <= height; i++){
string += Array(height-i+1).join(' ') + Array(2*i).join('#') + '<br>';
}
document.write(string);
</script>
<style>body{font-family:monospace;}</style>
You get this:
#
###
#####
#######
#########
###########
#############
###############
#################
###################
I've never done this before and am not sure why it's outputting the infamous � encoding character. Any ideas on how to output characters as they should (ASCII+Unicode)? I think \u0041-\u005A should print A-Z in UTF-8, which Firefox is reporting is the page encoding.
var c = new Array("F","E","D","C","B","A",9,8,7,6,5,4,3,2,1,0);
var n = 0;
var d = "";
var o = "";
for (var i=16;i--;){
for (var j=16;j--;){
for (var k=16;k--;){
for (var l=16;l--;){
d = c[i].toString()
+ c[j].toString()
+ c[k].toString()
+ c[l].toString();
o += ( ++n + ": "
+ d + " = "
+ String.fromCharCode("\\u" + d)
+ "\n<br />" );
if(n>=500){i=j=k=l=0;} // stop early
}
}
}
}
document.write(o);
The .fromCharCode() function takes a number, not a string. You can't put together a string like that and expect the parser to do what you think it'll do; that's just not the way the language works.
You could ammend your code to make a string (without the '\u') from your hex number, and call
var n = parseInt(hexString, 16);
to get the value. Then you could call .fromCharCode() with that value.
A useful snippet for replacing all unicode-encoded special characters in a text is:
var rawText = unicodeEncodedText.replace(
/\\u([0-9a-f]{4})/g,
function (whole, group1) {
return String.fromCharCode(parseInt(group1, 16));
}
);
Using replace, fromCharCode and parseInt
If you want to use the \unnnn syntax to create characters, you have to do that in a literal string in the code. If you want to do it dynamically, you have to do it in a literal string that is evaluated at runtime:
var hex = "0123456789ABCDEF";
var s = "";
for (var i = 65; i <= 90; i++) {
var hi = i >> 4;
var lo = i % 16;
var code = "'\\u00" + hex[hi] + hex[lo] + "'";
var char = eval(code);
s += char;
}
document.write(s);
Of course, just using String.fromCharCode(i) would be a lot easier...