Swap out each addition symbol with a blank space within a given text

I'm currently working on a Typescript project where I need to convert URL parameters into a JSON object.

The issue I'm facing is that some values are concatenated with a '+'. How can I replace this symbol with a space?

Here's the URL I'm dealing with:

let paramUrl = 'type=MERCEDES+BENZ'

This is what my code looks like:

let replace = JSON.parse('{"' + paramUrl.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })

Currently, it returns:

{type: "MERCEDES+BENZ"}

However, I actually need it to return:

{type: "MERCEDES BENZ"}

Answer №1

If you're not an expert in regular expressions, I would advise against using them for cases like this. Explicit character manipulation can make debugging and maintenance more challenging compared to utilizing available JavaScript APIs to convert your URL search params string into a simple object.

Here's a recommended approach, assuming that your JS runtime supports 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" }

This concise one-liner first transforms your paramUrl string into an object representing a list of key-value pairs, then converts these pairs into a plain object. You don't have to worry about maintaining or implementing URLSearchParams or Object.fromEntries(); just use or polyfill them (e.g., this polyfill for URLSearchParams).

If your search param string contains multiple values for the same key (e.g., foo=bar&foo=baz), only the last value will be retained. However, you can handle this by switching from Object.fromEntries() to a more customized iteration if necessary.

Playground link to code

Answer №2

Consider transforming your output by following these steps:

const modify = {category: "MERCEDES+BENZ"}
const modifiedModify = JSON.parse(JSON.stringify(modify).replace('+', ' '))
console.log(modifiedModify)

Alternatively, you can directly manipulate the data like so:

let transform = {category: "MERCEDES+BENZ"}
transform.category=transform.category.replace('+',' ')
console.log(transform)

Answer №3

Give this a shot

let paramUrl = 'type=MERCEDES+BENZ';
let arr=paramUrl.replaceAll("+"," ").split("=");
let obj={[arr[0]]:arr[1]}; // {type: "MERCEDES BENZ"}

Alternatively, you can achieve the same in one line

let obj= paramUrl.replaceAll("+"," ").split("=")
.reduce( (key,value) => { return { [key] : value}; } ); // {type: "MERCEDES BENZ"} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

Utilizing string literals as index signatures

I've created a code snippet called MyTest that maps over an object: type MyTest<T> = { [P in keyof T]: T[P]; }; type Result = MyTest<{hello: 'world', foo: 2}>; // ^? type Result = { hello: 'world', foo: 2 } ...

The compiler is unable to locate the node_module (Error: "Module name not found")

Error: src/app/app.component.ts:4:12 - error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try npm i @types/node and then add node to the types field in your tsconfig. 4 moduleId: module.id, When att ...

Modify the interface type whilst maintaining the structure of nested objects

In my system, I have a specific interface that outlines the structure of a NoSQL document schema. This includes strings, arrays, nested objects, and more. Here's an example representation: interface IStudentSchema { name: string; age: string; f ...

Encountering an error with TypeScript generic parameters: Expecting '?' but receiving an error message

As a newcomer to TypeScript, I am currently exploring the use of generic type parameters. I have encountered an error message: '?' expected while working on a function and a type that both require type arguments. The issue seems to be in the Inpu ...

Resolving issues with Typescript declarations for React Component

Currently utilizing React 16.4.1 and Typescript 2.9.2, I am attempting to use the reaptcha library from here. The library is imported like so: import * as Reaptcha from 'reaptcha'; Since there are no type definitions provided, building results ...

Exploring Improved Error Handling for Spring MVC REST Service and Client. Seeking more efficient solutions for managing errors

Seeking Improved Error Handling for Spring MVC REST Service and Client I am interested in enhancing the way errors are handled in my Spring MVC REST Service and Client. Sometimes I need to send an error message or a status code back to the client, but I a ...

What is the best way to determine the type of a key within an array of objects

Suppose I have the following code snippet: type PageInfo = { title: string key: string } const PAGES: PageInfo[] = [ { key: 'trip_itinerary', title: "Trip Itinerary", }, { key: 'trip_det ...

guide on displaying all json elements using javascript

I am struggling to create a card element for each row in the database using my function, but it only prints the first element. Can you help me identify what I forgot to include? (the query is working correctly) aggiornaEventi(); function aggiornaEventi ...

What is the role of @Output and EventEmitter in Ionic development?

I'm currently working on integrating Google Maps and Firebase database. My goal is to save my location in the Firebase database and transfer data using @Output and eventEmitter. However, I am facing an issue where pickedLocation has a value but this.l ...

Integrate TypeScript into the current project

As a newcomer to Typescript, I am currently exploring the option of integrating it into my current project. In our MVC project, we have a single file that houses the definitions of all model objects. This file is downloaded to the client when the user fir ...

Animated drop-down menu in Angular 4

I recently came across this design on web.whatsapp.com https://i.stack.imgur.com/ZnhtR.png Are there any Angular packages available to achieve a dropdown menu with the same appearance? If not, how can I create it using CSS? ...

Extract particular attributes from a specified JSON document

I'm currently facing an issue while trying to query information from a JSON file using a JSONPath expression with the JObject.selectTonkens() method. Unfortunately, I haven't been able to obtain the desired output. I've experimented with va ...

Using Django URL regex to handle JSON data

I seem to have hit a roadblock in my understanding of json queries. I am attempting to display json data on a view that has the URL structure provided below. http://localhost:8000/structures/hydrants/json?id=%3D2/ This is the regex I am using for the URL ...

To dismiss a popup on a map, simply click on any area outside the map

Whenever I interact with a map similar to Google Maps by clicking on various points, a dynamically generated popup appears. However, I am facing an issue where I want to close this popup when clicking outside the map area. Currently, the code I have writte ...

Utilizing Angular 2 to retrieve and assign object properties provided by a service to a local variable within a

My video service: public getExercise(exerciseId): Observable<Exercise[]>{ let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers, withCredentials: t ...

How can you make an IonPopover dynamically appear from a button with the perfect positioning?

I want to display a popover below a button when the button is clicked, similar to the example on the Ion docs page. However, I am having trouble implementing this in React as the code provided is only for Angular. Here is my current code: ... <IonButt ...

The web service consistently provides a combination of XML and JSON formats. Is there a way to convert it to solely

I have been assigned a project where I need to create a webservice that strictly returns JSON data. Despite my efforts, the code I've written always returns a combination of XML and JSON response. namespace DotMeTast { [WebService(Namespace = "h ...

Guide to customizing CSS styles within a div element using TypeScript code in a Leaflet legend

I'm struggling to add a legend to my map using Angular 5 and typescript. I need help with setting CSS styles for the values (grades) that are displayed on the legend. Can someone guide me on where to put the styles? TS: createLegend() { let lege ...

"Troubleshooting JSON parsing issues with simple_form and AJAX integration in a Ruby on

Currently, there is a form on the users dashboard that allows them to add a custom game rule. This form utilizes Simple Forms and remote => true, loaded via Jquery's .load() function from the "rules" view, which is managed by the rules controller. ...