user12915445
user12915445

Reputation:

Remove string + characters using regular expressions

I'm quite new to regex and I was wondering if there is a way of doing this in a one line regex expression

let error = '{"error":"invalid email address"}'
document.write("<p>old: <b>",error,"</b></p>")
error = error.replace(/["\{\}:]/g,'')//this
error = error.replace(/error/g,"")//and this in one line
document.write("<p>new: <b>",error,"</b></p>")
p{
display: block;
}

Upvotes: 2

Views: 44

Answers (1)

Matt Ellen
Matt Ellen

Reputation: 11612

Use a capture group, created with (), and put the result of that group into the replace statement with $1 where you can replace 1 with the number of the capture group:

error = error.replace(/{"error":"(invalid email address)"}/g, '$1')

let error = '{"error":"invalid email address"}'
document.write(`<p>old:<b> ${error}</b></p>`)
error = error.replace(/{"error":"(invalid email address)"}/g, '$1')
document.write("<p>new: <b>",error,"</b></p>")
p{
display: block;
}

If the string "invalid email address" can change, then you'll want to capture any string except ", which you can do with:

error = error.replace(/{"error":"([^"]+)"}/g, '$1')

Upvotes: 2

Related Questions