Home > Back-end >  Left and right trim string in javascript
Left and right trim string in javascript

Time:03-22

I have a string format that is of this format {"message ":"System: you are now connected as ghi"}

I want to trim it such that I get this System: you are now connected as user as final string. I guess in JS we cannot trim a string and we can only trim white spaces so how do I get this

CodePudding user response:

Your KEY has a trailing space

const message = JSON.parse(`{"message ":"System: you are now connected as ghi"}`)["message "]

console.log(message)

CodePudding user response:

if you are trying to access the message with spaced key you can do as follow:

const str = '{"message ":"System: you are now connected as ghi"}'

const obj = JSON.parse(str);

console.log(obj["message "])

if you are trying to remove the space out of the keys of your object you can do as follow:

const str = '{"message ":"System: you are now connected as ghi"}'

const obj = JSON.parse(str);

Object.keys(obj).filter(entry => entry !== entry.trim())
                .forEach(entry => {
                     const trimmedEntry = entry.trim();
                     obj[trimmedEntry] = obj[entry];
                     delete obj[entry];
                 })
console.log(obj)

  • Related