I have a string with contain some single quote, I want to replace all the single quote present inside string with double quote excluding the single quote preset inside {} [] () . Any pointer will be really helpful trying to solve this using JAVASCRIPT.
Actual String :
let str =`name:'John' {hobbies:'Playing'} , (age: '45')`;
console.log(str);
Expected Output:
name:"John" {hobbies:'Playing'} , (age: '45')
Check out .replaceAll.
In order to replace just the single quotes around John, you'll probably want to use a bit of Regex.
let str = "name:'John' {hobbies:'Playing'} , (age: '45')";
str = str.replaceAll(/(name:)'([^']+?)'/g, "$1\"$2\"");
console.log(str);
// name:"John" {hobbies:'Playing'} , (age: '45')
You can use the method str.replaceAll("'", '"');
let braceTracker = 0;
// convert string into an array of string using spread operator
// alternatively you can do str.split("")
let str = [..."name:'John' {hobbies:'Playing'} , (age: '45')"];
for (let x = 0; x < str.length; x++)
{
if(str[x] === "[" || str[x] === "{" || str[x] === "(")
braceTracker++;
else if(str[x] === "]" || str[x] === "}" || str[x] === ")")
braceTracker--;
else if(str[x] === "'" && braceTracker === 0)
str[x] = "\"";
}
console.log(str.join(""));
// output : name:"John" {hobbies:'Playing'} , (age: '45')