Using JavaScript, I am trying to replace text if its in parentheses and the the parentheses has a specific character (A) before it.
A string can look like this:
A(This text) should (say) hello.
Here A(This text) should be replaced with You, but (say) should not be replaced at all, because it does not have the character A before it. Also the character A has to be in uppercase.
I have tried with regex but I find it very hard to understand. Right now I can only remove A and then replace whats inside parentheses, but this also removes other text inside parentheses that does not have A before them.
This is what I got:
const string = "A(This text) should (say) hello."
function runIt() {
const replace = string.replace(/ *\A() */g, "You") //Removes "A"
let replace2 = replace.replace(/ *\([^)]*\) */g, " ") //"Removes all text inside all parentheses
console.log(replace2) //Result is: "You should hello.", it should say: "You should (say) hello.
}
runIt();
Use
\bA\([^()]+\)
See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
A 'A'
--------------------------------------------------------------------------------
\( '('
--------------------------------------------------------------------------------
[^()]+ any character except: '(', ')' (1 or more
times (matching the most amount possible))
--------------------------------------------------------------------------------
\) ')'
JavaScript code
const string = "A(This text) should (say) hello."
function runIt(string) {
let replace2 = string.replace(/\bA\([^()]+\)/g, 'You')
console.log(replace2)
}
runIt(string)