Replace an Array to represent as a string - Logic Error - javascript

I have a Javascript array in the following format;
["One","Two","Three"]
I want this to be a string in the following format;
('One','Two','Three')
I tried the following; but it says TypeError: arr.replace is not a function (I guess this is because arr is an array)
arr=arr.replace("[","(");
arr=arr.replace("]",")");
How can replace the strings [ " ] with ( ' ) as described above.

You can use Array.join():
> var a = ["One","Two","Three"];
> "('" + a.join("','") + "')"
"('One','Two','Three')"

Well, you cannot use .replace on Array. You can do the following though
var arr = ["One","Two","Three"];
arr = "('" + arr.join("', '") + "')";

You can use this code to convert your array to string
var arr = ["One","Two","Three"]​;
var str = "('"+arr.join("','")+"')";
alert(str);
​
Fiddle Demo

You have to convert it to be a string, not an array instance. Try this:
arrStr = arr.toString();
arrStr=arrStr.replace("[","(");
arrStr=arrStr.replace("]",")");
EDIT I remembered incorrectly, this would not provide the appropriate results... The output would be:
One,Two,Three.
The recommended solution is posted first by #Blender, joining the array parts together, and adding the required opening and closing brackets...
If you have to solve this with using only replace(), this would get the proper result:
arrStr = arr.toString();
arrStr=arrStr.replace(",","','");
arrStr = "('" + arrStr "')";

Related

Problems with first blank value while building a delimiter parser using regex

I'm building this generic parser that decodes a string to an Array using an specified delimiter.
For this question, I'll use comma as delimiter.
This is my current regex:
var reg = /(\,|\r?\n|\r|^)(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|([^"\,\r\n]*))/gi
It works fine for most cases like:
'a,b,c,d'.match(reg);
returns
["a", ",b", ",c", ",d"] (having the commas with the values is not a problem)
When I have empty values, it also works, for example:
'a,,c,'.match(reg);
returns ["a", ",", ",c", ","] (this is also fine)
The problem is when I have a blank value at the first position:
',b,c,d'.match(reg);
returns [",b", ",c", ",d"] and I was expecting something like: ["", ",b", ",c", ",d"]
Any ideas?
If you want to split by , then the regex is very simple: /,/g.
You can then pass this pattern into the split function.
It will also work with multi-character delimiters e.g. foo.
You can then do something like this:
var pattern = /,/g;
var el = document.getElementById('out');
el.insertAdjacentHTML('beforeend', '<p>Trying with ,</p>');
output('a,b,c,d');
output(',b,c,d');
output(',,,d');
output('a,,c,');
el.insertAdjacentHTML('beforeend', '<p>Trying with foo</p>');
var pattern = /foo/g;
output('afoobfoocfood');
output('foobfoocfood');
output('foofoofood');
output('afoofoocfoo');
function output(input) {
var item = '<p>' + input + ' gives: ';
var arr = input.split(pattern);
item += '<pre>' + JSON.stringify(arr) + '</pre></p>';
el.insertAdjacentHTML('beforeend', item);
}
<div id="out"></div>
How about something simpler like this regex:
[^\,]*\,(?!$)|[^\,]|\,
The regex above will catch anything between , including special characters. You can build on it to make it match specific type of characters.
This is a working js:
var reg = /[^\,]*\,(?!$)|[^\,]|\,/gi;
var s = ',,b,c,d'.match(reg);
document.write(s[0], '<br>' , s[1] , '<br>' , s[2] , '<br>' , s[3], '<br>' , s[4]);
Thanks to everyone who posted an answer but I ended up going with the solution provided here:
Javascript code to parse CSV data
The solution above also had the problem with an empty value at the first position but solving that with JS in the while loop was easier than fixing the RegEx.

Add to current string using javascript

I would like to add to the current string using javascript. Currently, It is working fine but I am doing it in a very dirty way currently. I am basically replacing the WHOLE string instead of just adding to it. Is there a way that I can just add a comma and continue my string?
JS:
var mystring = "'bootstrap'"
console.log(mystring.replace(/bootstrap/g , "'bootstrap', 'bootstrap2', 'bootstrap3'"));
JSFiddle
You can add to the end of a string by using the +=operator. See the docs regarding string operators.
var mystring = "'bootstrap'"
mystring += ", 'bootstrap2'";
mystring += ", 'bootstrap3'";
console.log(mystring);
You can concatenate( + operator ) instead of replace if you just want the second string to get appended to the first string.
var mystring = "'bootstrap'"
var newString = mystring +", "+ "'bootstrap', 'bootstrap2', 'bootstrap3'";
console.log( newString );
What about:
mystring += "'bootstrap2',";
or
var arr = ["str1", "str2", "str3"];
var mystring = arr.map((e)=>{return "'"+e+"'";}).join(",")
Array.map function used to wrap each string with single quates, than you Array.join - used to put "," between members
You can concat strings with the + operator:
var mystring = "'bootstrap'" + ",";
console.log(mystring);
Use an array and the join method.
var arr = [];
var myString = "bootstrap";
arr.push(myString);
arr.push(myString);
arr.push("other string");
arr.push("bootstrap");
// combine them with a comma or something else
console.log(arr.join(', '));
It is not suggested, but if you want to keep symbols and not care about order, and want to only add to a string beginning with 'bootstrap':
myString = "'bootstrap'";
console.log(myString.replace(/^(?='(bootstrap)')/, "'$12', '$13', "));
or you can just use capture group to keep it short
mystring.replace(/'(bootstrap)'/, "'$1', '$12', '$13'")

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

append single quotes to characters

I have a string like
var test = "1,2,3,4";
I need to append single quotes (' ') to all characters of this string like this:
var NewString = " '1','2','3','4' ";
Please give me any suggestion.
First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').
var test = "1,2,3,4";
var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");
JS Fiddle demo (please open your JavaScript/developer console to see the output).
For multiple-digits:
var newString = test.replace(/(\d+)/g, "'$1'");
JS Fiddle demo.
References:
Regular expressions (at the Mozilla Developer Network).
Even simpler
test = test.replace(/\b/g, "'");
A short and specific solution:
"1,2,3,4".replace(/(\d+)/g, "'$1'")
A more complete solution which quotes any element and also handles space around the separator:
"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")
Using regex:
var NewString = test.replace(/(\d+)/g, "'$1'");
A string is actually like an array, so you can do something like this:
var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
testOut += "'" + test[i] + "'";
}
That's of course answering your question quite literally by appending to each and every character (including any commas etc.).
If you needed to keep the commas, just use test.split(',') beforehand and add it after.
(Further explanation upon request if that's not clear).

Convert string with commas to array

How can I convert a string to a JavaScript array?
Look at the code:
var string = "0,1";
var array = [string];
alert(array[0]);
In this case alert shows 0,1. If it where an array, it would show 0. And if alert(array[1]) is called, it should pop-up 1
Is there any chance to convert such string into a JavaScript array?
For simple array members like that, you can use JSON.parse.
var array = JSON.parse("[" + string + "]");
This gives you an Array of numbers.
[0, 1]
If you use .split(), you'll end up with an Array of strings.
["0", "1"]
Just be aware that JSON.parse will limit you to the supported data types. If you need values like undefined or functions, you'd need to use eval(), or a JavaScript parser.
If you want to use .split(), but you also want an Array of Numbers, you could use Array.prototype.map, though you'd need to shim it for IE8 and lower or just write a traditional loop.
var array = string.split(",").map(Number);
Split it on the , character;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
This is easily achieved in ES6;
You can convert strings to Arrays with Array.from('string');
Array.from("01")
will console.log
['0', '1']
Which is exactly what you're looking for.
If the string is already in list format, you can use the JSON.parse:
var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);
Convert all type of strings
var array = (new Function("return [" + str+ "];")());
var string = "0,1";
var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var stringArray = (new Function("return [" + string+ "];")());
var objectStringArray = (new Function("return [" + objectstring+ "];")());
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/
Result in console
Some practice doesnt support object strings
- JSON.parse("[" + string + "]"); // throw error
- string.split(",")
// unexpected result
["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", " {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"", " CatGroupName:"Leather"", " Gender:"child"}"]
For simple array members like that, you can use JSON.parse.
var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";
var array = JSON.parse("[" + listValues + "]");
This gives you an Array of numbers.
now you variable value is like array.length=1
Value output
array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes
You can use split
Reference:
http://www.w3schools.com/jsref/jsref_split.asp
"0,1".split(',')
Another option using the ES6 is using Spread syntax.
var convertedArray = [..."01234"];
var stringToConvert = "012";
var convertedArray = [...stringToConvert];
console.log(convertedArray);
use the built-in map function with an anonymous function, like so:
string.split(',').map(function(n) {return Number(n);});
[edit] here's how you would use it
var string = "0,1";
var array = string.split(',').map(function(n) {
return Number(n);
});
alert( array[0] );
How to Convert Comma Separated String into an Array in JavaScript?
var string = 'hello, world, test, test2, rummy, words';
var arr = string.split(', '); // split string on comma space
console.log( arr );
//Output
["hello", "world", "test", "test2", "rummy", "words"]
For More Examples of convert string to array in javascript using the below ways:
Split() – No Separator:
Split() – Empty String Separator:
Split() – Separator at Beginning/End:
Regular Expression Separator:
Capturing Parentheses:
Split() with Limit Argument
check out this link
==> https://www.tutsmake.com/javascript-convert-string-to-array-javascript/
You can use javascript Spread Syntax to convert string to an array. In the solution below, I remove the comma then convert the string to an array.
var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])
I remove the characters '[',']' and do an split with ','
let array = stringObject.replace('[','').replace(']','').split(",").map(String);
More "Try it Yourself" examples below.
Definition and Usage
The split() method is used to split a string into an array of substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is split between each character.
Note: The split() method does not change the original string.
var res = str.split(",");
Regexp
As more powerful alternative to split, you can use match
"0,1".match(/\d+/g)
let a = "0,1".match(/\d+/g)
console.log(a);
Split (",") can convert Strings with commas into a String array, here is my code snippet.
var input ='Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, Android Wear API'
var output = input.split(",");
console.log(output);
["Hybrid App", " Phone-Gap", " Apache Cordova", " HTML5", "
JavaScript", " BootStrap", " JQuery", " CSS3", " Android Wear API"]
var i = "[{a:1,b:2}]",
j = i.replace(/([a-zA-Z0-9]+?):/g, '"$1":').replace(/'/g,'"'),
k = JSON.parse(j);
console.log(k)
// => declaring regular expression
[a-zA-Z0-9] => match all a-z, A-Z, 0-9
(): => group all matched elements
$1 => replacement string refers to the first match group in the regex.
g => global flag
Why don't you do replace , comma and split('') the string like this which will result into ['0', '1'], furthermore, you could wrap the result into parseInt() to transform element into integer type.
it('convert string to array', function () {
expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
});
Example using Array.filter:
var str = 'a,b,hi,ma,n,yu';
var strArr = Array.prototype.filter.call(str, eachChar => eachChar !== ',');

Categories

Resources