How to write comma separated value in single quote in java script? - javascript

I have a dynamic list of emails which are separated by comma, and I want to put all in single comma
In example:
(a#zyz.com,b#xyz.com,c#xyz.com,d#xyz.com) to ('a#zyz.com','b#xyz.com','c#xyz.com','d#xyz.com')
I tried to resolve it, but didn't succeed.

Supposing you want to enclose emails with single quotes, you can split on , and then Array.map and then Array.join
var str = "a#zyz.com,b#xyz.com,c#xyz.com,d#xyz.com";
str = str.split(",").map(function(str){
return "'" + str + "'"; // add quotes
}).join(",") // join the array by a comma

use split method of javascript.
E.g.
var str = "a#zyz.com,b#xyz.com,c#xyz.com,d#xyz.com";
var res = str.split(',');

Related

Is there a simple one-liner to split and join a string?

I have a string which looks likes this:
obj.property1.property2
I want the string to become
[obj][property1][property2]
Currently I use a split and later on a for loop to join each other. But I was wondering if there was a more simpler method for doing this, perhaps with using split() and join() toghether. I can't figure out how however.
Currently using:
var string = "obj.property1.property2";
var array = string.split(".");
var output = "";
for(var i = 0;i < array.length;i++) {
output += "[" + array[i] + "]";
};
console.log(output);
Consider using replace with the RegEx global option to replace all instances of '.' with back to back braces, then stick an opening and closing brace on the end like this.
var str ="obj.property1.property2"
console.log("["+str.replace(/\./g,"][")+"]")
'['+string.split('.').join('][')+']'

What will be the efficient way to Replace characters from within braces?

I have the below input
var input = (a-d){12-16},(M-Z){5-8},[#$%!^,12+-,23^!]
I need to remove the comma within the square brackets such that the final output will be
var output = (a-d){12-16},(M-Z){5-8},[#$%!^12+-23^!]
By solution
function test()
{
var input = '(a-d){12-16},(M-Z){5-8},[#$%!^,12+-,23^!]'; //input string
var splitByFirstBracket = input.split("["); //split the input by [ character
//merge the arrays where the second array is replaced by '' for ','
var output = splitByFirstBracket[0] + '[' + splitByFirstBracket[1].replace(/,/g,'');
alert(output);
}
It is providing the output correctly. Is there any better way - I am open both for JavaScript and JQuery.
Thanks in advance
You can use a regular expression replacement. The replacement can be a function, which receives the part of the input that was matched by the regexp, and then it can calculate the replacement. In this case, it would use another replace call to remove the commas.
var input = '(a-d){12-16},(M-Z){5-8},[#$%!^,12+-,23^!]'; //input string
var output = input.replace(/\[.*?\]/g, function(match) {
return match.replace(/,/g, '');
});
console.log(output);

how can i replace first two characters of a string in javascript?

lets suppose i have string
var string = "$-20455.00"
I am trying to swap first two characters of a string. I was thinking to split it and make an array and then replacing it, but is there any other way? Also, I am not clear how can I achieve it using arrays? if I have to use arrays.
var string = "-$20455.00"
How can I achieve this?
You can use the replace function in Javascript.
var string = "$-20455.00"
string = string.replace(/^.{2}/g, 'rr');
Here is jsfiddle: https://jsfiddle.net/aoytdh7m/33/
You dont have to use arrays. Just do this
string[1] + string[0] + string.slice(2)
You can split to an array, and then reverse the first two characters and join the pieces together again
var string = "$-20455.00";
var arr = string.split('');
var result = arr.slice(0,2).reverse().concat(arr.slice(2)).join('');
document.body.innerHTML = result;
try using the "slice" method and string concatenation:
stringpart1 = '' //fill in whatever you want to replace the first two characters of the first string with here
string2 = stringpart1 + string.slice(1)
edit: I now see what you meant by "swap". I thought you meant "swap in something else". Vlad's answer is best to just switch the first and the second character.
Note that string[0] refers to the first character in the string, and string[1] to the second character, and so on, because code starts counting at 0.
var string = "$-20455.00";
// Reverse first two characters
var reverse = string.slice(0,2).split('').reverse().join('');
// Concat again with renaming string
var result= reverse.concat(string.slice(2));
document.body.innerHTML = result;
let finalStr = string[1] + string[0] + string.slice(2); //this will give you the result

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 !== ',');

Put quotes around a variable string in JavaScript

I have a JavaScript variable:
var text = "http://example.com"
Text can be multiple links. How can I put '' around the variable string?
I want the strings to, for example, look like this:
"'http://example.com'"
var text = "\"http://example.com\"";
Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:
"http://example.com"
var text = "http://example.com";
text = "'"+text+"'";
Would attach the single quotes (') to the front and the back of the string.
I think, the best and easy way for you, to put value inside quotes is:
JSON.stringify(variable or value)
You can add these single quotes with template literals:
var text = "http://example.com"
var quoteText = `'${text}'`
console.log(quoteText)
Docs are here. Browsers that support template literals listed here.
Try:
var text = "'" + "http://example.com" + "'";
To represent the text below in JavaScript:
"'http://example.com'"
Use:
"\"'http://example.com'\""
Or:
'"\'http://example.com\'"'
Note that: We always need to escape the quote that we are surrounding the string with using \
JS Fiddle: http://jsfiddle.net/efcwG/
General Pointers:
You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Or you can put quotes inside a string by using the \ escape
character:
Example
var answer='It\'s alright';
var answer="He is called \"Johnny\"";
Or you can use a combination of both as shown on top.
http://www.w3schools.com/js/js_obj_string.asp
let's think urls = "http://example1.com http://example2.com"
function somefunction(urls){
var urlarray = urls.split(" ");
var text = "\"'" + urlarray[0] + "'\"";
}
output will be text = "'http://example1.com'"
In case of array like
result = [ '2015', '2014', '2013', '2011' ],
it gets tricky if you are using escape sequence like:
result = [ \'2015\', \'2014\', \'2013\', \'2011\' ].
Instead, good way to do it is to wrap the array with single quotes as follows:
result = "'"+result+"'";
You can escape " with \
var text="\"word\"";
http://jsfiddle.net/beKpE/
Lets assume you have a bunch of urls separated by spaces. In this case, you could do this:
function quote(text) {
var urls = text.split(/ /)
for (var i = 0; i < urls.length; i++) urls[i] = "'" + urls[i] + "'"
return urls.join(" ")
}
This function takes a string like "http://example.com http://blarg.test" and returns a string like "'http://example.com' 'http://blarg.test'".
It works very simply: it takes your string of urls, splits it by spaces, surrounds each resulting url with quotes and finally combines all of them back with spaces.
var text = "\"http://www.example1.com\"; \"http://www.example2.com\"";
Using escape sequence of " (quote), you can achieve this
You can place singe quote (') inside double quotes without any issues
Like this
var text = "'http://www.ex.com';'http://www.ex2.com'"
Another easy way to wrap a string is to extend the Javascript String prototype:
String.prototype.quote = function() { return "\"" + this + "\""; };
Use it like this:
var s = "abc";
console.log( "unwrapped: " + s + ", wrapped: " + s.quote() );
and you will see:
unwrapped: abc, wrapped: "abc"
This can be one of several solutions:
var text = "http://example.com";
JSON.stringify(text).replace('\"', '\"\'').replace(/.$/, '\'"')

Categories

Resources