dev
dev

Reputation: 916

extract the certain part of a string

I have a below string i need to extract certain part of the string.

 input :  'response:"The check has enabled" '
    
 output:  The check has enabled

Is there any better way, i have achieved with the below snippet.

let string = 'response:"The check has enabled" '
let output = string.replace(
  `response:"`,
  ""
)

output = output.substring(0, output.length - 2);

console.log(output)

Upvotes: 0

Views: 355

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

You can use a regular expression to match text between "s:

const string = 'response:"The check has enabled" '
const output = string.match(/(?<=")[^"]+(?=")/)[0];
console.log(output)

If you control the API that creates the string that needs to be parsed, it would be far better to change it so that it gives you JSON instead, and then you can use JSON.parse on it, and just access the .response property of the object.

Upvotes: 1

Related Questions