wrap json data separated by commas with quotes - javascript

How can i go round wrapping a given string separated with commas in jquery with quotes
Say
respons_pre =response[0].s_date; //in code
response_pre= 10/01/2015, 10/02/2015, 11/20/2015;
so as to be like
response_pre2='10/01/2015', '10/02/2015', '11/20/2015';

Just use replace() to replace every occurance of , with ', ' for this & add quotes in starting & end of string.
respons_pre =response[0].s_date;
var responseString = "\'"+response_pre.replace(/, /g,'\', \'')+"\'";
Working Example:
var response_pre= "10/01/2015, 10/02/2015, 11/20/2015";
var responseString = "\'"+response_pre.replace(/, /g,'\', \'')+"\'";
document.body.innerHTML= "Response String: "+response_pre+'<br/>'+"Output String: "+responseString;

If I understood your question, you have an array of Date objects, which you would like to transform into a string containing the dates represented in the MM/dd/yyyy format, enclosed with single quotes, joined with a comma and a space.
I would do it this way :
respons_pre.map(function(date) { return "'" + date.toLocaleDateString() + "'"; }).join(', ');
Explanation :
map will apply a transformation to each element of the array
toLocaleDateString transform a date object to a locate string representation (if you want to force en-US format, it can be passed as a parameter)
we also add the enclosing single quotes in the transformation function
finally we join the elements of the resulting string array with a comma and a space

response_pre =response[0].s_date;
responseArr = response_pre.split(", ");
responseArrWithQuotes = responseArr.map(function(dateString) {
return "\'" + dateString + "\'";
});
responseString = responseArrWithQuotes.toString();
responseString is the result you're looking for.
Please do note that my answer demands that the string response_pre separates the dates with ,, (comma and space), not only a comma.

Related

String (double quote) formatting in Javascript

I have a string
var st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104"
Now I want to put a double quote around each substring
i.e required string
var st = ""asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104""
Is this possible to achieve anything like this in javascript?
If you meant to transform a string containing "words" separated by comma in a string with those same "words" wrapped by double quotes you might for example split the original string using .split(',') and than loop through the resulting array to compose the output string wrapping each item between quotes:
function transform(value){
const words = value.split(',');
let output = '';
for(word of words){
output += `"${word.trim()}", `;
}
output = output.slice(0, -2);
return output;
}
const st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104";
const output = transform(st);
console.log(output);
That's true unless you just meant to define a string literal containing a character that just needed to be escaped. In that case you had several ways like using single quotes for the string literal or backticks (but that's more suitable for template strings). Or just escape the \" inside your value if you are wrapping the literal with double quotes.
You can use backticks ``
var st = `"asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104"`
You can split the string by the comma and space, map each word to a quote-wrapped version of it and then join the result again:
const result = myString
.split(', ')
.map(word => `"${word}"`)
.join(', ')
Also you can transform your string with standard regular expressions:
// String
let st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv _ jkl4 _ 100x104";
// Use regular expressions to capture your pattern,
// which is based on comma separator or end of the line
st = st.replace(/(.+?)(,[\s+]*|$)/g, `"$1"$2`);
// Test result
console.log(st);

Search in string and quote around occurrence

Working with Javascript I need to be able to search a string input from a user and replace occurrences of semicolons with commas. Issue I have ran into is I need to be able to search the string for any commas that already exist, and quote around to the last and next occurrence of the semicolon.
Example:
User input is 12345;Joran,Michael;02;17;63 it should be converted to 12345,"Joran,Michael",02,17,63
My includes is able to locate the occurrence of a comma in the original string var srch = source.includes(","); and my replace is var converted = source.replace(/;/g, ","); which works fine, just need to figure out how to get to the last/next semicolon to place the quotes.
Using an if/else depending on if srch evaluates to True -- if true, add the quotes and then convert the rest of the string and return to the user; if false, convert and return.
I'm sure there's a way to do this with regex that just hasn't came to me yet so any suggestions on what to look at would be great.
I'd do this in two steps. First match non-; characters which have at least one ,, and surround them with quotes. Then replace all ;s in the result with ,:
console.log(
'12345;Joran,Michael;02;17;63'
.replace(/[^;,]*,[^;]*/g, '"$&"')
.replace(/;/g, ',')
);
Split the string by ;
.split(';')
which gives you an array.
Convert the elements that include a ',' to "${element}"
.map(s => s.includes(',') ? `"${s}"` : s )
Convert the array back to string
.join(',')
var str = '12345;Joran,Michael;02;17;63';
var arr = str.split(";");
var letters = /^[A-Za-z]/;
var final_str = "";
for (var i = 0; i < arr.length; i++) {
final_str = arr[i].match(letters)?final_str +'"'+ arr[i]+'"'+",":final_str + arr[i]+",";
}
console.log(final_str.substring(0,final_str.length -1));

Get double quotes for the searchTerms result query in the URL with Javascript

var searchTerms = escape(jQuery('input#q').val());
var st = searchTerms.trim();
var res = st.replaceAll("TITLE","ti").replaceAll("%20","%20and%20").replaceAll("AUTHOR","au");
I have the above code and need the search term values in double quotes as the result
It gives result URL as : '&query=heartmate%20and%20owens'
But I need it as : '&query="heartmate"%20and%20"owens"'
The simplest way is to map the values to new values before you inject them into the request. But first you need to split the string into its individual terms...
let terms = st.split(' ');
that will return an array of the individual elements of the string, split on a space character,
then you can trim and append the term...
terms.map(term => {
term.trim(); // <-- this removes all of the whitespace characters, including
// space, tab, no-break space, and all the line terminator
// characters, including LF, CR, etc. from the beginning and end
// of the string
return '"' + term + '"';
});
You may find the need to check a condition of term before applying the map, it really depends on what you're doing.
You can use backslash \ to escape your character
var test = " \" \" ";
console.log(test);

Parse unicode in string using $.each

I'm trying to filter a string from a onmousemove event (tooltip).
The filtered string needs to be showed as text.
The problem is that the string looks like:
This string needs to be filtered. \r\n There is also unicode in this string \u00EB.
What I want:
This string needs to be filtered. There is also unicode in this string: ë
The HTML looks as follows:
<img onmousemove="showInfo(event,'This string needs to be filtered. \r\n There is also unicode in this string: \u00EB.');" onmouseout="hideInfo();" />
This is what I tried:
$(document).ready(function() {
$('td > img').each(function() {
var toolTip = $(this).attr('onmousemove'),
comment = toolTip.match(/([\'])(\\?.)*?\1/),
parentCell = $(this).parent();
$("div.timelineRow").css("padding", "7px");
$("<td><b>Info:</b><span> " + comment[0] + "</span></td>").insertAfter(parentCell);
$(this).insertAfter(parentCell);
});
});
Try decoding your Unicode character using JSON.parse. (Note the wrapping in double quotes to make it valid JSON).
Then replace the new lines with <br> tags to convert them into HTML line break elements (The browser won't render \r\n).
e.g.
var htmlComment = JSON.parse('"' + comment[0] + '"').replace("\r\n", "<br>");
$("<td><b>Info:</b><span> " + htmlComment + "</span></td>").insertAfter(parentCell);

Javascript: String of text to array of characters

I'm trying to change a huge string into the array of chars. In other languages there is .toCharArray(). I've used split to take dots, commas an spaces from the string and make string array, but I get only separated words and don't know how to make from them a char array. or how to add another regular expression to separate word? my main goal is something else, but I need this one first. thanks
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.toLowerCase();
str = str.split(/[ ,.]+/);
You can use String#replace with regex and String#split.
arrChar = str.replace(/[', ]/g,"").split('');
Demo:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
var arrChar = str.replace(/[', ]/g,"").split('');
document.body.innerHTML = '<pre>' + JSON.stringify(arrChar, 0, 4) + '</pre>';
Add character in [] which you want to remove from string.
This will do:
var strAr = str.replace(/ /g,' ').toLowerCase().split("")
First you have to replace the , and . then you can split it:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
var strarr = str.replace(/[\s,.]+/g, "").split("");
document.querySelector('pre').innerHTML = JSON.stringify(strarr, 0, 4)
<pre></pre>
var charArray[];
for(var i = 0; i < str.length; i++) {
charArray.push(str.charAt(i));
}
Alternatively, you can simply use:
var charArray = str.split("");
I'm trying to change a huge string into the array of chars.
This will do
str = str.toLowerCase().split("");
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.
Please read the link:
http://www.w3schools.com/jsref/jsref_split.asp
You may do it like this
var coolString,
charArray,
charArrayWithoutSpecials,
output;
coolString = "If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
// does the magic, uses string as an array to slice
charArray = Array.prototype.slice.call(coolString);
// let's do this w/o specials
charArrayWithoutSpecials = Array.prototype.slice.call(coolString.replace(/[', ]/g,""))
// printing it here
output = "<b>With special chars:</b> " + JSON.stringify(charArray);
output += "<br/><br/>";
output += "<b>With special chars:</b> " + JSON.stringify(charArrayWithoutSpecials)
document.write(output);
another way would be
[].slice.call(coolString)
I guess this is what you are looking for. Ignoring all symbols and spaces and adding all characters in to an array with lower case.
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.replace(/\W/g, '').toLowerCase().split("");
alert(str);

Categories