I've got something like this data that comes from API and I need to do JSON.parse this, but the problem was there were inner double quotes so I can't parse it what should I do, can I use regex or something.
const dataString = '{"EN" : "2. This English "Blha Blha" "Woo Woo" something wrong."}';
I also used this regex
replace(/(^"|"$)|"/g, "'");
but by using this regex it's replace all the double quotes with single quotes like this =>
{'EN' : '2. This English 'Blha Blha' 'Woo Woo' something wrong.'};
I only want to replace the quotes like this
{'EN' : '2. This English "Blha Blha" "Woo Woo" something wrong.'};
The thing is that single quotes are not valid symbols for JSON if they are used to wrap key/values. To make it clear - you need to escape double-quote symbols in values. A better approach is to update your API with that correction. More ugly but working way is placed below:
const dataString = '{"EN" : "2. This English "Blha Blha" "Woo Woo" something wrong."}';
const normalize = (dataString) => {
let newString = dataString;
newString = newString.replaceAll(`"`, `\\\"`);
newString = newString.replaceAll(`{\\\"`, `{"`);
newString = newString.replaceAll(`\\\"}`, `"}`);
newString = newString.replaceAll(`\\\" : \\\"`, `" : "`);
return newString;
};
console.log(JSON.parse(normalize(dataString)));
Related
How can I get the word in between quotation marks and then replace it with something else from reading from a file
Note: I know how to read and write from files, I just need to know about getting the word from inside quotation marks
If you know the word you're looking for:
let text = 'Sentence with "word" in it';
let wordFromFile = "nothing";
let newText = text.replace('"word"', wordFromFile);
Or else regular expression is useful.
Using Regex(regular expression) with regex replace :
let str = 'How can I get the word in between "quotation marks"';
let word = str.replace(/.*"(.*?)".*/g,'$1');
let replacedWord = 'single quotes';
console.log(str.replace(word,replacedWord))
You can find the word with a quotation mark for example word by /"[^"]+"/ and replace it with other words for example key
const str = 'This is the "word" which inside two quotation marks'
const result = str.replace(/"[^"]+"/g, 'key')
console.log(result)
I have a long string
Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
removable_str2 = 'ab#xyz.com;';
I need to have a replaced string which will have
resultant Final string should look like,
cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
I tried with
str3 = Full_str1.replace(new RegExp('(^|\\b)' +removable_str2, 'g'),"");
but it resulted in
cab#xyz.com;c-c.c_ab#xyz.com;
Here a soluce using two separated regex for each case :
the str to remove is at the start of the string
the str to remove is inside or at the end of the string
PS :
I couldn't perform it in one regex, because it would remove an extra ; in case of matching the string to remove inside of the global string.
const originalStr = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;ab#xyz.com;c_ab#xyz.com;';
const toRemove = 'ab#xyz.com;';
const epuredStr = originalStr
.replace(new RegExp(`^${toRemove}`, 'g'), '')
.replace(new RegExp(`;${toRemove}`, 'g'), ';');
console.log(epuredStr);
First, the dynamic part must be escaped, else, . will match any char but a line break char, and will match ab#xyz§com;, too.
Next, you need to match this only at the start of the string or after ;. So, you may use
var Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
var removable_str2 = 'ab#xyz.com;';
var rx = new RegExp("(^|;)" + removable_str2.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "g");
console.log(Full_str1.replace(rx, "$1"));
// => cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
Replace "g" with "gi" for case insensitive matching.
See the regex demo. Note that (^|;) matches and captures into Group 1 start of string location (empty string) or ; and $1 in the replacement pattern restores this char in the result.
NOTE: If the pattern is known beforehand and you only want to handle ab#xyz.com; pattern, use a regex literal without escaping, Full_str1.replace(/(^|;)ab#xyz\.com;/g, "$1").
i don't find any particular description why you haven't tried like this it will give you desired result cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
const full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
const removable_str2 = 'ab#xyz.com;';
const result= full_str1.replace(removable_str2 , "");
console.log(result);
I have received the following string from my ajax request:
As per json doc, "quotes must be escaped "
This is stored in data.description and is embedded in the template as:
''
data-title's value is used as a caption for lightbox plugin pop up. I tried the following function:
var HtmlEncode = function(s) {
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
as:
''
Now since the data.description contains multiple quotes javascript assumes them as multiple argument and throws error. I searched many other Stackoverflow posts which suggest to append the data in a div and retrieve its inner HTML but that is possible in my case.
Thanks
Change only the quotes that are the same as those will be surrounding the data-title. Like this:
var description = data.description.replace(/"/g, "'");
var template = '';
You can replace the double quotes in your string with single quotes or any other symbol in order for it to work inside double quotes.
you can do this with String.replace(/["]+/g,"'") this will replace the double quotes in the string with a single quote, the g in the reg-ex tells it to use all the string.
you can also fake it by using 2 single quotes like this String.replace(/["]+/g,"''"), and it will fake double quotes for you.
var HtmlEncode = function(s) {
return s.replace(/["]+/g,"''");
}
Solution 1
Escape it with replace and a regexp:
var HtmlEncode = function(s) {
return s.replace(/"/g, '\\"').replace(/'/g, "\\'");
}
''
Solution 2
Let jQuery doing this for you (only if you are using it).
var tpl = $('');
tpl.data('title', data.description);
Try to replace the quotes with HTML entity equivalents after which you can then safely use it on attributes.
var desc = data.description.replace(/'/g, "'").replace(/"/g, """);
''
Here's a Fiddle to demonstrate the solution.
I have a string and I need to replace all the ' and etc to their proper value
I am using
var replace = str.replace(new RegExp("[']", "g"), "'");
To do so, but the problem is it seems to be replacing ' for each character (so for example, ' becomes '''''
Any help?
Use this:
var str = str.replace(/'/g, "'");
['] is a character class. It means any of the characters inside of the braces.
This is why your /[']/ regex replaces every single char of ' by the replacement string.
If you want to use new RegExp instead of a regex literal:
var str = str.replace(new RegExp(''', 'g'), "'");
This has no benefit, except if you want to generate regexps at runtime.
Take out the brackets, which makes a character class (any characters inside it match):
var replace = str.replace(new RegExp("'", "g"), "'");
or even better, use a literal:
var replace = str.replace(/'/g, "'");
Edit: See this question on how to escape HTML: How to unescape html in javascript?
Rather than using a bunch of regex replaces for this, I would do something like this and let the browser take care of the decoding for you:
function HtmlDecode(s) {
var el = document.createElement("div");
el.innerHTML = s;
return el.innerText || el.textContent;
}
Currently I have a basic regex in javascript for replacing all whitespace in a string with a semi colon. Some of the characters within the string contain quotes. Ideally I would like to replace white space with a semi colon with the exception of whitespace within quotes.
var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+/g, ":");
alert(stringout);
Thanks
Robin
Try something like this:
var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, ":");
Note that it will break when there are escaped quotes in your string:
"ab \" cd" ef "gh ij"
in javascript, you can easily make fancy replacements with callbacks
var str = '"james \\"bigboy\\" johnson" joe "wendy johnson" tony';
alert(
str.replace(/("(\\.|[^"])*")|\s+/g, function($0, $1) { return $1 || ":" })
);
In this case regexes alone are not the simplest way to do it:
<html><body><script>
var stringin = "\"james \\\"johnson\" joe \"wendy johnson\" tony";
var splitstring = stringin.match (/"(?:\\"|[^"])+"|\S+/g);
var stringout = splitstring.join (":");
alert(stringout);
</script></body></html>
Here the complicated regex containing \\" is for the case that you want escaped quotes like \" within the quoted strings to also work. If you don't need that, the fourth line can be simplified to
var splitstring = stringin.match (/"[^"]+"|\S+/g);