EDIT: This string is a part of json and i am writing it onto a file. In that json file i see the escape charaters. With console.log, I don't see any escape character.
I am trying to concatenate a string such that I get the following output:
"OR("1admin", "2admin")"
But the output I keep on getting is
"OR(\"1admin\", \"2admin\")"
Sample code
var str = "OR("
for (let i = 1; i < 3; i++) {
str += '"' + i + 'admin' + '", ';
}
str = str.trim().substring(0, str.length - 2).concat(')')
console.log(str)
I have tried using regex and string split.
eg.
.replace(/'/g, '"') This when i tried something like this "'" + i + "admin" + "', " and tried to replace ' with "
.split('\\').join('').trim() This also didn' work.
What am I doing wrong?
As mentioned, you already got the correct result in your original snippet.
If the character escape syntax seems curious to you, I'd recommend something like the following using template strings.
You can write the " in template strings unescaped and use interpolation to print your variables.
Edit: Seems like you want JSON formatting. You can use JSON.stringify for that. JSON formatted strings will contain escape characters that show up in console.log output.
const f = (n, s) => {
const a = new Array(n)
.fill()
.map((_, i) => `"${i + 1}${s}"`);
return `OR(${a.join(', ')})`;
}
console.log(`output: ${f(2, "admin")}`)
console.log(`json-formatted: ${JSON.stringify(f(2, "admin"))}`)
This seems to do the job:
const NUM_ADMINS = 2;
const CONCAT_STRING =
`OR(${
Array(NUM_ADMINS)
.fill()
.map((_, idx) => `"${idx + 1}admin"`)
.join(", ")})`;
It creates a new array with the needed number of admins, then maps it to strings in th form "admin", joins with a comma and a space. And then it it is all wrapped in a "OR()" string.
var str = '"OR("'
var adm = 'admin"'
var end = ')"'
for (let i = 1; i < 3; i++) {
str += i + adm + ', '
}
str = str.trim().substring(0, str.length - 2)
str += end
console.log(str);
try running this snippet. if the implementation is fyn for you. Result is what you expected.
Related
I am very new to coding. I am having issue solving this following:
taking a data block ex:
1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42
and covert into something like
1963,"john, doe","Williwanka,tp",jane,4200,1300,19.63,-42
I know I can use split() and join() however having trouble sorting through the string separated by comma "," and add double quote.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var myArray = text.split(";");
var newText = "";
for (var i = 0; i <= myArray.length; i++) {
if (myArray.indexOf(i) == ",") {
let newText = '"' + fruits.join('","') + '"';
} else {
newText += text.index(i);
}
}
return newText
Split by semicolons, then for each part, check if it includes a comma. If it does, wrap it in quotes, otherwise, don't change it. Then join the result into a string.
const text = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42";
const parts = text.split(";");
const result = parts.map((p) => p.includes(",") ? `"${p}"` : p).join(",");
console.log(result);
You could use the regex /([^;]+)(?:;|$)/ and replace the first capturing group with " if it cannot be parsed to a number.
const input = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42",
replacer = (_, p1) => isNaN(p1) ? `"${p1}",` : `${p1},`,
output = input.replace(/([^;]+)(?:;|$)/g, replacer).slice(0, -1);
console.log(output)
While the previous answers are correctly fine, it might be hard to understand how they work for a novice programmer.
Allow me to fix give you another answer below which is based on a simple loop like the OPs original code.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var partsArray = text.split(";");
var newText = "";
for (var i = 0; i < partsArray.length; i++) {
let onePart = partsArray[i];
if (onePart.includes(",")) {
newText += `"${onePart}"`;
} else {
newText += onePart;
}
newText += ",";
}
console.log(newText);
I want to split a string for a fill in string type with no whitespace for examples:
£____
____$
42____$
i would like a way to split the string so i can know what the characters before and after _.
Desired results:
`£____` => before = '£', after = null
`____$` => before = null, after = '$'
`42____$` => before = '42', after = '$'
I though of tried using word.replace('_', ' ') to split by whitespace but it returning the same string as the old one(i'm still a novice at javascript).
You may try a regex string split here:
var inputs = ["£____", "____$", "42____$"];
for (var i=0; i < inputs.length; ++i) {
var parts = inputs[i].split(/_+/);
console.log("before = " + parts[0] + ", after = " + parts[1]);
}
You can try Regex.
Something Like This
[^_;]
I am new to javascript, i tried to modify a text shown below with substring command.
eg. "ABCD_X_DD_text" into "ABCD-X(DD)_text" this
i used this
var str = "ABCD_X_DD_cover";
var res = str.substring(0,4)+"-"+str.substring(5,6)+"("+str.substring(7,9)+")"+str.substring(9,15);
// print to console
console.log(res);
i got what i want. But problem is X and DD are numerical (digit) value. and they are changeable. here my code just stop working.
it can be ..... "ABCD_XXX_DDDD_text" or "ABCD_X_DDD_text".
could you suggest some code, which works well in this situation.
You can use a split of the words.
var strArray = [
"ABCD_X_DD_cover",
"ABCD_XX_DD_cover",
"ABCD_XXX_DD_cover"
];
for(var i = 0; i < strArray.length; i++){
var split = strArray[i].split("_");
var str = split[0] + "-" + split[1] + "(" + split[2] + ") " + split[3];
console.log(str);
}
I used a for cycle using an array of strings, but you can do it with a variable too.
I have a string csv containing PORTCODE and latitude longitude of location. I use these values to plot the marker on google map.
Eg csv string:
ANC|61.2181:149.9003,
ANC|61.2181:149.9003,
TLK|62.3209:150.1066,
DNL|63.1148:151.1926,
DNL|63.1148:151.1926,
DNL|63.1148:151.1926,
TLK|62.3209:150.1066,
TLK|62.3209:150.1066,
ALE|60.9543:149.1599
i want to autonumber SIMILAR PORTCODE sequence separated with pipe symbol '|' for the PORTCODE which are EXACT Consecutive next element.
Required out put:
ANC|61.2181:149.9003:1|2,
TLK|62.3209:150.1066:3,
DNL|63.1148:151.1926:4|5|6,
TLK|62.3209:150.1066:7|8,
ALE|60.9543:149.1599:9
Any solution using jquery/javascript/c# ?
There's probably a neater/shorter way to do this, but here's the first second way that came to mind using JavaScript:
var input = "ANC|61.2181:149.9003,\nANC|61.2181:149.9003,\nTLK|62.3209:150.1066,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nTLK|62.3209:150.1066,\nTLK|62.3209:150.1066,\nALE|60.9543:149.1599";
var output = input.split(",\n").reduce(function(p,c,i,a) {
if (i === 1) p += ":1";
return p + (c === a[i-1] ? "|" : ",\n" + c + ":") + (i+1);
});
console.log(output);
I've assumed each line ends with a single \n character, but obviously you can adjust for \r or whatever.
Further reading:
the string .split() method
the array .reduce() method
You can make something like that.
var csv = 'ANC|61.2181:149.9003,\nANC|61.2181:149.9003,\nTLK|62.3209:150.1066,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nTLK|62.3209:150.1066,\nTLK|62.3209:150.1066,\nALE|60.9543:149.1599'.split(',\n');
//count entry :
var results = [];
var j = -1;
var previous = "";
for (i = 0; i < csv.length; i++) {
if (previous === csv[i]) {
results [j] += '|' + (i+1);
} else {
j += 1;
previous = csv[i];
results [j] = csv[i] + ':' + (i+1);
}
}
//And reforme your csv
console.log(results.join(',\n'));
Further reading:
the string .split() method
the array .join() method
here is C# way to do,
public string[] data = { "ANC|61.2181:149.9003", "ANC|61.2181:149.9003", "TLK|62.3209:150.1066", "DNL|63.1148:151.1926", "DNL|63.1148:151.1926", "TLK|62.3209:150.1066", "TLK|62.3209:150.1066", "ALE|60.9543:149.1599", "DNL|63.1148:151.1926" };
int counter = 0;
var output = data.Select(x => new Tuple<string, int>(x, counter++))
.GroupBy(x => x.Item1)
.Select(h => h.Key + ":"+ string.Join("|", h.Select(x => x.Item2)));
output would be ANC|61.2181:149.9003:0|1,TLK|62.3209:150.1066:2|5|6,DNL|63.1148:151.1926:3|4|8,ALE|60.9543:149.1599:7
so I need to be able to enter a string and have it reversed. I must have one library JS file and one regular JS file. Here is my library JS file:
function reverseString(string) {
var reversedString= "";
for(var i = string.length -; i >=; --i) {
reversedString = reversedString + string[i];
}
return reversedString;
}
and here is my regular one
var stringEntered = prompt("Enter a string:")
var newString = reverseString(stringEntered);
document.write("the reverse of the string \" + stringEntered + \ " is \" + newString + ".")
I entered it the exact same way my professor showed us, and I when I try to run my HTML file (which is coded to call both these files), nothing happens. What am I missing?
There're a lot of syntax issues. Here's a working code:
function reverseString(string) {
var reversedString = "";
// This loop had a lot of basic syntax issues and also
// "i" was starting from the length value, while a string
// is a character array and array indexes start from 0 instead of 1
for (var i = string.length - 1; i >= 0; --i) {
reversedString = reversedString + string[i];
}
return reversedString;
}
var stringEntered = prompt("Enter a string:");
var newString = reverseString(stringEntered);
// Here I found a mess of "/" characters
// I've changed the horrible document.write with alert so you can check the result without opening the debugger...
alert("the reverse of the string " + stringEntered + " is " + newString + ".")
Here is a concise method of reversing a string:
function reverseString(string) {
return string.split('').reverse().join('');
}
var str = prompt("Enter a string", "a racecar dad");
alert(reverseString(str));
Turn it into an array, reverse the array, turn it back into a string.
Edit: Sorry, didn't see #SidneyLiebrand's comment telling you to do the same.