Replacing a string with object property - javascript

I have a string
var str="{name:'qwer',age:24,gender:'male'}"
and I have an object with same property
var object = {name : zxcvb}
By matching the property (name) of the object, I want to overwrite the property value inside the string with the value from the object. The desired output is:
newString = "{name:'zxcvb',age:24,gender:'male'}"
Please let me know if you need any clarifications. Can we achieve this by regex?

You can iterate over the object, building a RegExp out of the key and substituting the value on a match:
let str = "{name:'qwer',age:24,gender:'male',aname:'xyz',namey:'pqr'}";
const obj = {
name: 'zxcvb'
};
for (let [key, value] of Object.entries(obj)) {
const regex = new RegExp(`\\b${key}\\s*:\\s*'[^']+'`);
str = str.replace(regex, `${key}:'${value}'`);
}
console.log(str);

Related

How do I parse a string and get next 6 characters?

I have string like:
let str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
how do I parse this string to get for example only "245454" ? I assume it must be based on 'nicetomeetyou=' the value after '=' is always 6 characters.
You can use split to extract the parts (name and value), and Object.fromEntries to turn those pairs into an object. Then you can access each value by property of that object:
const toObject = (str) =>
Object.fromEntries(str.split("^").map(eq => eq.split("=")));
// Demo
let str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
let obj = toObject(str);
console.log(obj.Hello);
Note that in the example string, EP has no corresponding =, and in that case the object returned by toObject will have undefined assigned to the property EP. To test whether that EP property actually exists, you can use the in operator:
const toObject = (str) =>
Object.fromEntries(str.split("^").map(eq => eq.split("=")));
// Demo
let str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
let obj = toObject(str);
console.log("EP" in obj); // true
So you reinvented querysting with a different separator. Make it an & and you can just use built in URLSearchParams
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const urlParams = new URLSearchParams(str.replace(/\^/g, '&'));
console.log(urlParams.get("Hello"));
console.log(urlParams.get("nicetomeetyou"));
console.log(urlParams.get("howdoIdothis"));
If you want to keep it with the ^, a split and map
var str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const params = Object.fromEntries(str.split("^").map(s => s.split(/=/)));
console.log(params["Hello"]);
console.log(params["nicetomeetyou"]);
console.log(params["howdoIdothis"]);
If you only care about the 3 values
var str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP"
var re = /=([^\^]+)/g;
var out = [];
while(match = re.exec(str)) out.push(match[1]);
console.log(out);
And since you only seem to care about one value
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const val = str.match(/nicetomeetyou=(.{6})/)[1]
console.log(val);
You could replace all the ^ values with & and run it through URLSearchParams to get the value that you are looking for:
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const params = new URLSearchParams(str.replace(/\^/g, '&'))
console.log(params.get('nicetomeetyou'))

splitting string into an object JavaScript

I have this String result:tie,player:paper,computer:paper
I guess you could split into arrays and make a object and parse it an object, however this does not seem to be a good approach.
How would I get this String as a object?
let string = "result:tie,player:paper,computer:paper"
For this particular string, I'd turn the string into proper JSON by surrounding the keys and values with "s, and then use JSON.parse:
const string = "result:tie,player:paper,computer:paper";
const json = '{' + string.replace(/(\w+):(\w+)/g, `"$1":"$2"`) + '}';
console.log(JSON.parse(json));
Though, ideally, whatever serves you that string should be giving you something in JSON format, rather than forcing you to resort to a hacky method like this to deal with a broken input.
Split on ,, iterate through, and split each string on : and make an object key/value property based on that. Use destructuring for simplicity:
let string = "result:tie,player:paper,computer:paper";
let obj = {};
let propsArr = string.split(",");
propsArr.forEach(s => {
var [key, value] = s.split(":");
obj[key] = value;
});
console.log(obj);
Split on the , to get key:value tokens, split those by : to get the key and value, and add them to the reduced object that collects the key value pairs.
var temp = "result:tie,player:paper,computer:paper";
var obj = temp.split(',').reduce((result, token)=>{
var [key, value] = token.split(':');
result[key] = value;
return result;
}, {});
console.log(obj);

How to convert JavaScript object into LITERAL string?

If I have the object literal:
{a: "hello"}
Is there a Javascript function to convert this object into a literal string, so that the output would be the literal syntax:
'{a: "hello"}'
With JSON.stringify the output would be
'{"a": "hello"}'
You can do it with JSON.stringify and then with String.replace like follows:
var jsObj =
{
abc: "hello",
bca: "allo",
cab: "dd:cc",
d: ["hello", "llo", "dd:cc"],
e: {abc: "hello", bca: "allo", cab: "dd:cc"}
};
function format(obj)
{
var str = JSON.stringify(obj, 0, 4),
arr = str.match(/".*?":/g);
for(var i = 0; i < arr.length; i++)
str = str.replace(arr[i], arr[i].replace(/"/g,''));
return str;
}
console.log(format(jsObj));
JavaScript has no built-in functions that will convert an object to a string representation of it which either:
Uses identifiers instead of strings for property names
Represents the original syntax used to create the object
You could write your own function for the former (at least when the property name can be represented as a literal) but the latter is impossible as JavaScript stores no information about the source code used to create the object in the first place.
Ok just for fun...roll your own?
const stringify = (obj) => {
// Iterate over keys, reducing to a string
let str = Object.keys(obj).reduce((acc, cur) => {
let next = `${cur}: "${obj[cur]}"`;
return acc
? `${acc}, ${next}`
: `{${next}`;
}, '');
// Return, appending final '}'
return `${str}}`;
}
document.write(stringify({
foo:1,
bar:'seat'
}));
That said, your exact requirements aren't clear so I'm not sure this will meet them. But it might be a starting point if there's no native solution that works.
It does convert it to the literal syntax. You are able to create objects with multiple forms of syntax. Both of the following object declarations are valid:
var a = {a: "a"}
var b = {"b": "b"}
If you want to remove the "" around the key you should be able to match them with the following regex /\"(.*?)\":/g and replace them with something like this:
function reformat(str) {
var myRegexp = /\"(.*?)\":/g;
match = myRegexp.exec(str);
while (match != null) {
str = str.replace(match[0], match[1] + ":");
match = myRegexp.exec(str);
}
return str;
}
Hope that helps :)

How to fetch a value from a string in javascript?

I want to fetch a particular value from a javascript string without using methods like indexOf or substr. Is there any predefined method of doing so?
For e.g., I have a string,
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
I want to fetch the value of c from above string, how can I achieve it directly?
You can try with:
str.split('|').find(value => value.startsWith('c=')).split('=')[1]
You can also convert it into an object with:
const data = str.split('|').reduce((acc, val) => {
const [key, value] = val.split('=');
acc[key] = value;
return acc;
}, {});
data.c // 3
In this case, use split:
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var parts = str.split('|');
var value = parts[2].split('=')[1];
console.log(value);
Or maybe map it, to get all values to work with afterwards:
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var values = str.split('|').map(e => e.split('='));
console.log(values);
Using regex can solve this problem
const str = "a=1|b=2|c=3|d=4|e=5|f=6";
const matches = str.match(/c=([0-9]+)/);
console.log(matches[1]);
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
Try this -
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
str.split('|')[2].split('=')[1];
You could turn that string into an associative array or an object
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var obj = {}; //[] for array
str.split("|").map(o => {
var el = o.split("=");
obj[el[0]] = el[1];
})
console.log(obj.a)
console.log(obj.b)
console.log(obj.c)
I suggest first splitting and mapping into some form of readable data structure. Finding by string is vulnerable to typos.
const mappedElements = str
.split('|')
.map(element => element.split('='))
.map(([key, value]) => ({ key: value }));
Array filter method can be memory efficient for such operation.
var cOutput = str.split('|').filter( (val) => {
const [k,v] = val.split('=');
return k=='c' ? v : false }
)[0].split('=')[1];
See Array Filter

convert string to object key more than 2depths

I want to convert string to object's key
I know this logic
const object = { name : 'test' }
const string = name
object[string] = name
I have something problems about this.
const string = common.device.type.pc.name
object[string] <- this is not working
You can do this by split string to each value
values = string.split(".");
object[values[0]][values[1]][values[2]][values[3]][values[4]]
Example:
object = {value1: {value2: "123"}};
string = "value1.value2";
values = string.split(".");
object[values[0]][values[1]] //return "123"

Categories