Javascript Array.join with escaped string characters - javascript

we are facing an issue with the Array.prototype.join method in Javascript.
We have a string Array with HTML string parts.
These parts contain several escaped double primes (\").
Within the title and the text of our HTML element, we have the string
4" display
The array we use join on looks like this:
var myArray = [
"<a href=\"",
"http://www.example.com/",
"\"",
" ",
"title=\"",
"4\" display",
"\"",
">",
"4\" display",
"</a>"
];
myArray.join('');
And the output of this code snippet resolves to:
'4" display'
As you can see, this is not really the HTML element we hoped for.
We hope to create something like this instead:
'4\" display'
We tried to escape the backslashes once more:
"4\\\" display",
but this just resolved to
'4\\" display'
Also, we do not have control over the title and text here (input data from a source we can't control), so we cannot use a different ASCI character for the double primes.
We also tried to change the array entries to template strings instead:
var myArray = [
`<a href="`,
`http://www.example.com/`,
`"`,
` `,
`title=\"`,
`4\" display`,
`\"`,
`>`,
`4\" display`,
`</a>`
];
myArray.join('');
But the result is the same:
'4" display'
Is there any way to write this differently, so the join will respect the escape sequence?
Thanks and best regards,
Marius

You need to take three backslashes, two for getting a backslash and another for ".
const
parts = [
"<a href=\"",
"http://www.example.com/",
"\"",
" ",
"title=\"",
"4\\\" display", // <- escape here
"\"",
">",
"4\" display",
"</a>"
];
console.log(parts.join(''));

Related

Regex JS: Selecting all spaces not within quotes for multiple quotes in a row

So I need to select all spaces not between quotes and delete them, I am using regex in Javascript notation.
For example:
" Test Test " ab c " Test" "Test " "Test" "T e s t"
becomes
" Test Test "abc" Test""Test ""Test""T e s t"
UPDATE:
I am looking for a solution that would work in the above test setting:
https://www.regextester.com/
The goal is to effectively tokenize this long sentence by these spaces not included within quotes, but I figured the answer to the above question was more concise and easier to read/answer.
All Spaces not within quotes should be highlighted in the above setting. If they are highlighted in the above setting they would be parsed as follows:
[" Test Test ",ab,c," Test","Test ","Test","T e s t"]
My attempted solution was:
(,|;\s|\s)+(?![^\[]*\])(?![^\(]*\))(?![^\{]*\})(?![^"].*")
You may use this regex for .split:
\s+(?=(?:(?:[^"]*"){2})*[^"]*$)
This regex will split on spaces if those are outside double quotes by using a lookahead to make sure there are even number of quotes after space.
RegEx Demo
const str = '" Test Test " ab c " Test" "Test " "Test" "T e s t"';
var arr = str.split(/\s+(?=(?:(?:[^"]*"){2})*[^"]*$)/);
console.log(arr);
/* OUTPUT
[
"\" Test Test \"",
"ab",
"c",
"\" Test\"",
"\"Test \"",
"\"Test\"",
"\"T e s t\""
]
*/
Replace "quotes or space" with "the same thing or nothing":
input = `" Test Test " ab c " Test" "Test " "Test" "T e s t"`
result = input.replace(/(".*?")|( )/g, (_, $1, $2) => $1 || '')
console.log(result)
We can try a regex replacement approach with a callback function:
var input = '" Test Test " ab c " Test" "Test " "Test" "T e s t"';
var output = input.replace(/".*?"|[^"]+/g, (x) => x.match(/^".*"$/) ? x : x.replace(/\s+/g, ""));
console.log(output);
The strategy here is to match, alternatively, either a term in double quotes, or any other content not involving a doubly quoted term. The case of the former, we do no substitution. In the case of the latter, we remove all whitespace characters.
The answer is the following:
(,|;\s|\s+(?=(?:[^"]*"[^"]*"[^"]*)*$))+(?![^\[]*\])(?![^\(]*\))(?![^\{]*\})
First part handles selection of , ;\s and spaces and the second half makes sure they are not in quotes. Next part handles ignoring things not encased in quotes. And then the last part handles brackets etc.

How to replace double comma with a single comma in javascript

How can I convert this 2016-01-04 into this 2016-01-04 in JavaScript?
I have a dataset in an array with dates like this:
["x", "2016-01-04", "2016-01-05", "2016-01-06", "2016-01-07", "2016-01-08", "2016-01-09"]
And I want to covert them to:
['x', '2016-01-04', '2016-01-05', '2016-01-06', '2016-01-07', '2016-01-08', '2016-01-09']
I have tried .replace(/"/g, "'")
but I get an error forcastDate_ordered.replace is not a function
See Special Characters (JavaScript) from MSDN
Characters like the speech mark " and single quotation mark ' can be escaped with a backslash \ - this is helpful when they are in strings using speech marks or quotation marks around them.
And to replace the characters, use String.replace
So the final answer as others have stated is
string s = "\"2016-01-04\"";
return s.replace("\"", "'");
(The single quote is not escaped because the string is surrounded by speech marks " - so it doesn't need it)
UPDATE: your question is changed to involve arrays
In which case, you need Array.map
array.map(s => s.replace("\"", "'"));
var endString = startString.replace(/"/g, "'");
Example:
var startString = 'I hate "double" quotes';
var endString = startString .replace(/"/g, "'");
endString = I hate 'double' quotes
or
doubleQuotesReplacer = (startString) => startString .replace(/"/g, "'");

Adding array that has text with spaces into TextArea using JQuery and append()

I am trying to append to my page an array inside a TextArea and I break it every time I have a space between characters in array.
Let's say I have ingredients in array: "rice", "oil", "soy milk", "apple" I am using the following JQuery syntax:
$("#container").append("<input type = 'text' id = 'ingredients' value = " + ingArrayTest+ ">");
My final result will have only: "rice, oil, soy" because space will break the rest of the array in the display. Is there a way to wrap the array so it doesn't happen?
Thanks in advance!
You can use a simple array join, assuming I am reading this correctly. Try
ingArrayTest.join("\n")
... in place of ingArrayTest above. Spaces could be used in place of the '\n' ...
BASED ON DISCUSSION, try:
var ingArrayTest = ["Milk", "Soy Milk", "Apple"];
var ingString = ingArrayTest.join(" ");
$("#container").append("<input type='text' id='ingredients' value='" + ingString + "'>");
...note the single quotes near value. Watch single quotes versus double; very important.

replace "[ with [ and ]" with ] json

I have a JSON as below:
[{"type":"Point","coordinates":"[-77.03,38.90]"},"properties":{"city":3,"url":"xyz.com"}]
I want to replace "[ with [ and ]" with ]
try this
$yourJson = [{"type":"Point","coordinates":"[-77.03,38.90]"},"properties":{"city":3,"url":"xyz.com"}];
$jsonString=preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $yourJson);
$stringReplace=str_replace('"[', '[', $jsonString);
$stringReplace=str_replace(']"', ']', $stringReplace);
echo $stringReplace;
from the comment it seems you are putting additional quote " in replace try this
json = json.replace("\"[","[");
You can use the following regex:
str.replace(/"(\[[^"\]]*\])"/, "$1");
where str is the input string. This will match "[ followed by a string of any characters that are not " and ], followed by ]" and drop the two " at the extremes. In your case it will turn "[-77.03,38.90]" into [-77.03,38.90].
Aside from that, whoever coded what is returning the string in the question should be fired immediately.

Change Link Into Keywords with Javascript

I wanna change the url text into a words, but have no idea to do that. Please help me.
Here's what I wanna do, example:
some-text-url.html
into
some text url
Use the split method:
var url = "some-text-url.html";
url = url.replace(".html", ""); // remove html
var words = url.split("-");
// words is now an array of the keywords
var str = "some-text-url.html";
str = str.split('.')[0].split('-').join(' ');
.split() on the . gives an Array of:
[
"some-text-url",
"html"
]
[0] gives the first string in the Array "some-text-url"
.split() on the - gives an Array of:
[
"some",
"text",
"url"
]
And .join() passing a string with a single space gives the final result:
"some text url"
Or here's another way to avoid creating an Array with .split():
var str = "some-text-url.html";
str = str.replace(/-|\.html$/g," ");
Giving you "some text url ".
Notice the space on the end. If you don't want that, add .slice(-1) after the .replace().

Categories