How to append (connect) strings to construct a new string? - javascript

I have a array of strings:
str[1]='apple';
str[2]='orange';
str[3]='banana';
//...many of these items
Then, I would like to construct a string variable which looks like var mystr='apple,orange,banana,...', I tried the following way:
var mystr='';
for(var i=0; i<str.length; i++){
mystr=mystr+","+str[i];
}
Which is of course not what I want, is there any efficient way to connect all this str[i] with comma?

just use the built-in join function.
str.join(',');

Check out join function
var str = [];
str[0]='apple';
str[1]='orange';
str[2]='banana';
console.log(str.join(','));
would output:
apple,orange,banana

The fastest and recommended way of doing this is with array methods:
var str = [];
str[1] = 'apple';
str[2] = 'orange';
str[3] = 'banana';
var myNewString = str.join(',');
There have been various performance tests showing that for building strings, using the array join method is far more performant than using normal string concatenation.

You need this
var mystr = str.join(',');

how about 'join()'?
e.g.
var newstr = str.join();

You're looking for array.join i believe.
alert(['apple','orange','pear'].join(','));

Is this what you want?
var str = new Array(); //changed from new Array to make Eli happier
str[1]='apple';
str[2]='orange';
str[3]='banana';
var mystr=str[1];
for(var i=2; i<str.length; i++){
mystr=mystr+","+str[i];
}
console.log(mystr);
would produce
apple,orange,banana

Related

String into multiple string in an array

I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for(i = o; i <array.length; i++)
var loopedArray = array[i].split("|")
loopedArray.push(array2);
}
I have tried several other things but would take me awhile to put them all down.
You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);
Your code snippet is close, but you've messed up your variables in the push statement.
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for (i = 0; i < array.length; i++) {
var loopedArray = array[i].split("|")
array2.push(loopedArray);
}
array2 = array2.flat();
console.log(array2);
However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
.split('$')
.flatMap(arrayI => arrayI.split('|'));
console.log(array2);
And lastly, split already supports multiple delimiters when using regex:
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);
console.log(array2);
You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')
It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]
If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
Console.WriteLine(singleString);
}
the output is:
XX
Y1234
ZT
QW4567

How to remove substring and comma if exist on left or right side

I have the following string:
"house,car,table"
I need to properly handle the comma removal, so much so that If I remove "car" the output should be:
"house,table"
If I remove "table" the output should be:
"house,car"
You can use the .split() in an array then .filter() out the target text after words .join() to create a string.
var str = "house,car,table";
str = str.split(',').filter(x => x !== 'car').join(',');
console.log(str)
You can use string#split, string#indexOf array#splice and arr#join
var str = "house,car,table";
var arr = str.split(',');
var index = arr.indexOf('car');
arr.splice(index, 1);
console.log(arr.join(','));
There are several ways. #Satpal has offered a way that is optimized. but another way:
var array ="house,car,table";
var arraySplit = array.split(",");
var newArray = [];
for (i=0; i<arraySplit.length; i++)
{
if (arraySplit[i] != "car")
{
newArray.push(arraySplit[i]);
}
}
var joinedArray = newArray.join(",");
console.log(joinedArray);
function format(name){
var nameStr="house,car,table";
if(nameStr.indexOf(name)==-1)return -1;
nameStr+=",";
nameStr=nameStr.replace(name+",","");
return nameStr.substring(0,nameStr.length-1);
}
console.log(format("house"));
console.log(format("table"));

Removing return carriage from an array - Javascript

I have array as shown below:
["↵", "Oh", "yeah,", "did", "we", "mention", "it’s", "free?↵"]
Is there a way I can remove that ↵ from the string and from the array?
I tried
str.replace(/(\r\n|\n|\r)/gm,"");
This didn't help.
Simply split your string on /\s+/, then you don't need to perform this action anymore.
var str='\nOh yeah, did we mention it’s free?\n';
var arr=str.split(/\s+/);
Note: you might want to trim \s+ from the beginning and end of the string fist. (Older) Browsers that do not support trim() can use:
arr=str.replace(/^\s+|\s+$/g, '').split(/\s+/);
Strictly answering your question how to remove 'carriage returns' from strings in an array:
// you have:
var str= '\nOh yeah, did we mention it’s free?\n';
var arr= str.split(' ');
// no function needed, a simple loop will suffice:
for(var L=arr.length; L--; arr[L]=arr[L].replace(/[\n\r]/g, ''));
Note that (as can already be seen in your example as array-item 0) you might end up with some empty strings (not undefined) in your array.
You can clean up your array from empty strings using String.prototype.trim combined with Array.prototype.filter to remove falsy values. For example:
var arr = ["\n", "", "Oh", "yeah,", "did", "we", "mention", "it’s", "free?\n"]
// check array before
alert(JSON.stringify(arr));
arr = arr.map(function(el) {
return el.trim();
}).filter(Boolean);
// after cleaning up
alert(JSON.stringify(arr));
Try this:
function removeReturn(ary){
var b = [], a = [];
for(var i=0,l=ary.length; i<l; i++){
var s = ary[i].split('');
for(var n=0,c=s.length; n<c; n++){
if(s[n] === '\u021B5')s[n] = '';
}
b.push(s.join(''));
}
for(var i=0,l=b.length; i<l; i++){
var x = b[i];
if(x !== '')a.push(x);
}
return a;
}

How to print a String array in javascript?

String array :
var name=new String('Here','Is','Wasif');
I have tried this to print it :
for(var i=0;i< name.length;i++)
document.write(name[i]);
You don't have a string array.
Try
var name=['Here','Is','Wasif'];
for(var i=0;i< name.length;i++)
document.write(name[i]);
You can check this code
var arr = name=['Here','Is','Wasif'];
for(var i=0;i<arr.length;i++){
document.write(arr[i]);
}
You can try your code here :
http://jsfiddle.net/4Sgh5/
You could also use array join. A bit more simple that a for loop.
var arr = ['Here', 'Is', 'Wasif'];
document.write(arr.join(' '));

Elegant way to convert string of values into a Javascript array?

I have an ajax request that returns a list of values like this:
"1,2,3,4,5,6"
I need it to be a javascript array with numbers:
[1,2,3,4,5,6]
I tried:
var array = new Array("1,2,3,4,5,6".split(","))
But the numbers are still strings in the output:
["1","2","3","4","5","6"]
Is there a clean way to have it as a numbered array? Preferably without writing a function to iterate through it?
You need to loop through and convert them to numbers, like this:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = +array[i];
Or, the more traditional example:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = parseInt(array[i], 10);
A more jQuery-centric approach using jQuery.map():
var str = "1,2,3,4,5,6";
var arr = $.map(str.split(","), function(el) { return parseInt(el, 10); });
Not sure if this counts as writing a function but you can use the map function in jquery. I saw you listed as a tag so I assume you are using:
var stringArray = "1,2,3,4,5,6".split(",");
var numberArray = $.map(stringArray,
function(item, i)
{
return parseInt(item, 10);
});
// jquery must have a way to do what any modern browser can do:
var str= "1,2,3,4,5,6";
var arr= str.split(',').map(Number);
// returns an array of numbers
If you trust the ajax response, and if (for whatever reason) you're committed to not using a loop, you can always go with eval:
var str = "1,2,3,4,5,6";
var array = eval("[" + str + "]");
If you don't wish to expliclty iterate you can use array.map, javascripts map function.
array.map(callbackFunc, array);
var arr = array.map(function(x) {return parseInt(x);}, "1,2,3,4,5,6".split(","));
http://www.tutorialspoint.com/javascript/array_map.htm
Theres probably a better reference somewhere but I don't us javascript enough to have a good favorite reference site.
EDIT - i see jQuery has its own map, thats probably worth looking into.

Categories

Resources