Home > Software design >  Replace a with a space in a string
Replace a with a space in a string

Time:02-17

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"}

CodePudding user response:

Whether your conversion makes sense or not, you may convert your result with this:

const replace = {type: "MERCEDES BENZ"}
const replacedReplace = JSON.parse(JSON.stringify(replace).replace(' ', ' '))
console.log(replacedReplace)

Or manipulate the value directly:

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

CodePudding user response:

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.

Playground link to code

CodePudding user response:

try this

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