Incrementing a string by itself returning undefined - javascript

I am trying to print a simple stair pattern using asterisks.
for (i=0;i<7;i++) {
var asterisk = "*" + asterisk;
document.write(asterisk+"</br>");
}
Using this code returns the desired result, although "undefined is printed next to it.
*undefined
**undefined
***undefined
****undefined
*****undefined
******undefined
*******undefined
Why is this occurring? It appears to be caused by the addition of the variable to itself. I know this is possible with integers, although is there something different when using strings? Thanks.

Before your loop starts, the asterisk variable contains the undefined value.
Add this statement before the loop:
var asterisk = '';
And then remove the var inside the loop. It won't hurt, but you don't need it. And don't forget to use a var on the i loop variable. (Thanks RobG for the reminder!)
So you might end up with:
var asterisk = '';
for( var i = 0; i < 7; i++ ) {
asterisk = "*" + asterisk;
document.write( asterisk + "</br>" );
}

Declare asterisk outside of the loop and set it equal to an empty string. You aren't setting asterisk to any value so it defaults to undefined. That's why you are getting increments of "*undefined". Also, declare i with the var keyword as well.
var asterisk = '';
for (var i=0; i<7; i++) {
asterisk = "*" + asterisk;
document.write(asterisk+"</br>");
}

Related

How to remove string between two characters every time they occur [duplicate]

This question already has answers here:
Strip HTML from Text JavaScript
(44 answers)
removing html tags from string
(3 answers)
Closed 7 years ago.
I need to get rid of any text inside < and >, including the two delimiters themselves.
So for example, from string
<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>​
I would like to get this one
that
This is what i've tried so far:
var str = annotation.split(' ');
str.substring(str.lastIndexOf("<") + 1, str.lastIndexOf(">"))
But it doesn't work for every < and >.
I'd rather not use RegEx if possible, but I'm happy to hear if it's the only option.
You can simply use the replace method with /<[^>]*>/g.It matches < followed by [^>]* any amount of non> until > globally.
var str = '<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>';
str = str.replace(/<[^>]*>/g, "");
alert(str);
For string removal you can use RegExp, it is ok.
"<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>​".replace(/<\/?[^>]+>/g, "")
Since the text you want is always after a > character, you could split it at that point, and then the first character in each String of the array would be the character you need. For example:
String[] strings = stringName.split("<");
String word = "";
for(int i = 0; i < strings.length; i++) {
word += strings[i].charAt(0);
}
This is probably glitchy right now, but I think this would work. You don't need to actually remove the text between the "<>"- just get the character right after a '>'
Using a regular expression is not the only option, but it's a pretty good option.
You can easily parse the string to remove the tags, for example by using a state machine where the < and > characters turns on and off a state of ignoring characters. There are other methods of course, some shorter, some more efficient, but they will all be a few lines of code, while a regular expression solution is just a single replace.
Example:
function removeHtml1(str) {
return str.replace(/<[^>]*>/g, '');
}
function removeHtml2(str) {
var result = '';
var ignore = false;
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
switch (c) {
case '<': ignore = true; break;
case '>': ignore = false; break;
default: if (!ignore) result += c;
}
}
return result;
}
var s = "<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>";
console.log(removeHtml1(s));
console.log(removeHtml2(s));
There are several ways to do this. Some are better than others. I haven't done one lately for these two specific characters, so I took a minute and wrote some code that may work. I will describe how it works. Create a function with a loop that copies an incoming string, character by character, to an outgoing string. Make the function a string type so it will return your modified string. Create the loop to scan from incoming from string[0] and while less than string.length(). Within the loop, add an if statement. When the if statement sees a "<" character in the incoming string it stops copying, but continues to look at every character in the incoming string until it sees the ">" character. When the ">" is found, it starts copying again. It's that simple.
The following code may need some refinement, but it should get you started on the method described above. It's not the fastest and not the most elegant but the basic idea is there. This did compile, and it ran correctly, here, with no errors. In my test program it produced the correct output. However, you may need to test it further in the context of your program.
string filter_on_brackets(string str1)
{
string str2 = "";
int copy_flag = 1;
for (size_t i = 0 ; i < str1.length();i++)
{
if(str1[i] == '<')
{
copy_flag = 0;
}
if(str1[i] == '>')
{
copy_flag = 2;
}
if(copy_flag == 1)
{
str2 += str1[i];
}
if(copy_flag == 2)
{
copy_flag = 1;
}
}
return str2;
}

How to remove the last statement in a for loop

I am trying to construct a statement (because the client requests for it) and want to remove the last statement in a for loop but still included in between the loop.
This is what I am trying to achieve (as a broad example as I can):
I selected: 2 years period, 2 yrs period, 1 years period, 1 yrs period.
I managed to achieve this but at the very end, it doesn't end with a period, it ended with a comma instead.
The number of years is selected by the user, therefore I declared a variable.
Here is my code in Javascript:
var out_content = document.getElementById("content");
var in_year = 2;
var in_period = ["years","yrs"];
var sText = "I selected: ";
for (var i=0;i<in_year; in_year--)
{
for (var p=0;p<in_period.length;p++)
{
sText += in_year + in_period[p];
sText += ",";
}
}
out_content.innerHTML = sText;
What do I do?
The simplest way to solve your problem is to just remove the last character (the unwanted comma) and put a period there instead.
sText.slice(0,-1)+'.'
Slicing from 0 to -1 means getting the characters from the beginning to the one before the last.
Add the if statement before comma and check with the variable value with p and the condition should pass but should fail on last loop statement
Removing the last character from your string, when predictable, can be easily achieved as such:
sText = sText.substring(0, sText.length-2);
Substring takes two parameters, start (0) and end (you want length minus 1 here, but since its viewed as an array you might want length - 2). Heres more info: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring
A better way to handle this kind of problem is to use an array, then join array elements:
var sText = "I selected: ";
var aText = [];
for (var i=0;i<in_year; in_year--)
{
for (var p=0;p<in_period.length;p++)
{
aText.push(in_year + in_period[p]);
}
}
sText += aText.join() + '.';

Yet Another document.referrer.pathname Thing

I'm looking for the equivalent of "document.referrer.pathname". I know there are other questions that are similar to this on SO, but none of them handle all the use cases. For example:
http://example.com/RESULT
http://example.com/RESULT/
http://example.com/RESULT?query=string
All examples should return:
RESULT
or
https://example.com/EXTENDED/RESULT/
EXTENDED/RESULT
Some folks may want the trailing slash included, but I don't because I'm matching against a list of referrers.
I've started with:
document.referrer.match(/:\/\/.*\/(.*)/)[1]
and am struggling adding the query string parsing.
Thanks!
If you have URLs as strings you can create empty anchors and give them the url as href to access the pathname:
var url = 'http://example.com/RESULT?query=string', // or document.referrer
a = document.createElement('a');
a.href = url;
var result = a.pathname.replace(/(^\/|\/$)/g,'');
I set up a test example for you here: http://jsfiddle.net/eWydy/
Try this regular expression:
.match(/\/\/.*?\/(.*?)\/?(\?.*)?$/)[1]
DEMO
If you don't want to create a new element for it or rely on a.pathname, I'd suggest using indexOf and slice.
function getPath(s) {
var i = s.indexOf('://') + 3, j;
i = s.indexOf('/',i) + 1; // find first / (ie. after .com) and start at the next char
if( i === 0 ) return '';
j = s.indexOf('?',i); // find first ? after first / (as before doesn't matter anyway)
if( j == -1 ) j = s.length; // if no ?, use until end of string
while( s[j-1] === '/' ) j = j - 1; // get rid of ending /s
return s.slice(i, j); // return what we've ended up at
}
getPath(document.referrer);
If you want regex though, maybe this
document.referrer.match(/:\/\/[^\/]+[\/]+([^\?]*)[\/]*(?:\?.*)?$/)[1]
which does "find the first ://, keep going until next /, then get everything that isn't a ? until a ? or the last / or end of string and capture it", which is basically the same as the function I did above.

how to parse string

im trying to parse the following string;
"data[Product][0][fieldname]"
i need to be able to change the "[0]" part to a number, the "data[Product]" wont change while the "[fieldname]" will change.
im not sure how to do it with javascript but have an rough idea.
all i have which is wrong, is below but since [0] varies each time it doesnt work;
name="data[Product][0][fieldname]";
name.replace('[0]', '['+newrowid+']'
Jsfiddle;
http://jsfiddle.net/fuzzy_dunlop/8WKcs/
Use a regexp:
var a = "data[Product][0][fieldname]";
var re = /(.*\[.*\]\[)(.*)(\]\[.*\])/gi;
newstr = a.replace(re, "$1" + "YourString" + "$3");
document.write("Now: " + newstr);
Example code: http://jsfiddle.net/NKbd9/1/
Use this instead
name = name.replace('[0]', '['+newrowid+']');
Replace can take a regular expression instead of a string.
Try this:
name="data[Product][0][fieldname]";
name.replace(/\[\d\]/, '['+newrowid+']');
I assume you are trying to do this inside a loop, in that case you just need to make it dynamic. Also not that replace doesn't change the current string, it returns a new string so you need to assign the value returned back to name.
var i = 0,
len = 10,
name,
newrowid = 13;
for(; i <len; i++) {
name = "data[Product]["+i+"][fieldname]";
name = name.replace('['+i+']', '['+newrowid+']');
}

Any javascript string function?

Some outside code is giving me a string value like..
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
now i have to save this value to the data base but putting 0 in place of null in javascript. Is there any javascript string releated function to do this conversion?
You can simply use the replace function over and over again until all instances are replaced, but make sure that all your string will ever contain is the character sequence null or a number (and obviously the delimiting comma):
var str = "null,402,2912,null"
var index = str.indexOf("null");
while(index != -1) {
str = str.replace("null", "0");
index = str.indexOf("null");
}
You need to run a for loop because the function String.replace(search, rplc) will replace only the first instance of search with rplc. So we use the indexOf method to check, in each iteration, if the required term exists or not. Another alternative (and in my opinion, a better alternative would be:
var str = "null,402,2912,null"
var parts = str.split(",");
var data = []
for(var i=0; i<parts.length; i++) {
data[data.length] = parts[i]=="null"?0:parseInt(parts[i]);
}
Basically, what we are doing is that since you will anyways be converting this to an array of numbers (I presume, and sort of hope), we first split it into individual elements and then inspect each element to see if it is null and make the conversion accordingly.
This should answer your needs:
var str = 'null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390';
str.split(",").map(function (n) { var num = Number(n); return isNaN(num) ? 0 : num; });
The simplest solution is:
var inputString = new String("null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,");
var outputString = inputString.replace("null", "0");
What I understood from your question is:
You want to replace null with 0 in a string.
You may use
string = "null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,"
string.replace(/null/g,0)
Hope it helps.

Categories

Resources