replace "[ with [ and ]" with ] json - javascript

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.

Related

Javascript Array.join with escaped string characters

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(''));

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.

Regex Filter Arrays And Leave Specific Parts

Currently, I am trying to figure out a regex system where the input is ["title of the poll, polloption1 polloption2, polloption3 polloption4"].
How can I make it so that RegX filters out anything and returns to me ['polloption1 polloption2', 'polloption3 polloption4']?
My current code:
const s = ["title of the poll, polloption1 polloption2, polloption3 polloption4"];
console.log(s.split(/(?:^|")([^\s"]+)(?:\s+[^\s"]+)*/).filter(Boolean));
//returns: [ '+poll', ' ', 'option1', '" ', 'option2', '"' ] which is very inacurate
You can use
s[0].split(/\s*,\s*/).slice(1)
It yields [ "polloption1 polloption2", "polloption3 polloption4" ].
The /\s*,\s*/ regex matches any comma that is enclosed with zero or more whitespaces. The .slice(1) removes the first item from the resulting array.
See the regex demo.
See the JavaScript demo:
const s = ["title of the poll, polloption1 polloption2, polloption3 polloption4"];
console.log(s[0].split(/\s*,\s*/).slice(1));
console.log(["title of the poll, polloption1 polloption2, polloption3 polloption4"][0].split(/,\s+/).filter(x => /\w+\d\s\w+\d/.test(x)))

Split a string of strings by 2 delimeters

My string looks like
"<!number|Foo bar> <!number|Foo bar> <!number|foo bar>"
I have like to split the string by "<" and ">" so that the new array becomes
["<!number|string>", "<!number|string>" ].
I tried str.split('> <'), which gives me
["<!numer|string", "!number|string>"].
Also I tried using regex to str.split(/\<> /)
which gives me ["<!number|string> <!number|string>"].
How to split it correctly?
At work so I can't fix the nitty gritty with the regex, but the below works given the string
const str = `<!1|Foo bar> <!2|Bar Baz> <!3| xxx yyy>`;
console.log(str.split(/(<[\s\S]*?>)/gm).filter((n)=> { return (n!="" && n!=" ") }));
Just split on space:
let str = "<!number|string> <!number|string> <!number|string>";
console.log(str.split(" "));

How to bypass signle quote error in javascript?

I need to have an array as following but the single quote before (s) causes error. JavaScript does not accept them. Is there any way to bypass the error or replace the single quotes with other characters like space?
I tried to use replace function but not sure how to use it. I used ' but it did not work.
var locations = [
[
'Alex's loc', '37.9908372',
'23.7383394', '0'
],
[
'John James's loc', '37.9908372',
'23.7383394', '1'
],
[
'Norman's loc', '38.075352',
'23.807885', '3'
],
[
'Jack Moore's loc', '37.9908372',
'23.7383394', '2'
]
];
Code
var locations = [
<c:forEach var="location" items="${locationes}" varStatus="loop">[
'${location.value.name}', '${location.value.latitude}',
'${location.value.longitude}', '${loop.index}', </c:forEach> ];
you can wrap the single quote with double quote, like:
var locations = [
[
"Alex's loc", '37.9908372',
]
];
Using a backslash \ character before the invalid quote will also work. This is called an escape sequence
'Alex\'s loc' // this is represented as the string => Alex's loc
This is also how you get litteral new lines in strings
'\n' or "\n" for new line.

Categories