'Replace a + with a space in a string
I have a Typescript project where I am converting URL parameters to a JSON object.
The problem is that a value is concatenated with a '+', how can I replace this symbol with a space?
This is the URL:
let paramUrl = 'type=MERCEDES+BENZ'
This is what I do:
let replace = JSON.parse('{"' + paramUrl.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })
This is what it returns:
{type: "MERCEDES+BENZ"}
This is what I need:
{type: "MERCEDES BENZ"}
Solution 1:[1]
Unless you're very skilled with regular expressions I would strongly discourage using them for situations like this. In fact, any kind of explicit manipulation of characters here is going to be harder to debug and maintain than just using available JavaScript APIs to convert your url search params string into a plain object.
Here's how I'd suggest you proceed, assuming your JS runtime has both the URLSearchParams constructor and the Object.fromEntries() method:
let paramUrl = 'type=MERCEDES+BENZ'
const replace = Object.fromEntries(new URLSearchParams(paramUrl));
console.log(replace) // { "type": "MERCEDES BENZ" }
That's essentially a one-liner that first converts your paramUrl string into an object representing a list of string key-value pairs, and then converts these key-value pairs into a plain object. You're not responsible for maintaining or implementing URLSearchParams or Object.fromEntries(); you just have to use or polyfill them (e.g., this polyfill for URLSearchParams).
Be aware that if your search param string has multiple values for the same key (e.g., foo=bar&foo=baz) that you'll end up with just the latter one, but you can deal with that if you need to by switching from Object.fromEntries() to some more custom iteration.
Solution 2:[2]
try this
let paramUrl = 'type=MERCEDES+BENZ';
let arr=paramUrl.replaceAll("+"," ").split("=");
let obj={[arr[0]]:arr[1]}; // {type: "MERCEDES BENZ"}
or in one line
let obj= paramUrl.replaceAll("+"," ").split("=")
.reduce( (key,value) => { return { [key] : value}; } ); // {type: "MERCEDES BENZ"}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
