0

I've found plenty of old threads that recommend using \b to delineate words in a text document, so you can replace whole words, but I have expressions that contain words that might not be delineated by whitespace, such as

MyFunction(Fred, True, False, MyVariableIsTrue, x==true?a:b)

In this case I want to end up with

MyFunction(Fred, 1, 0, MyVariableIsTrue, x==1?a:b)

So my current code

        return expr
            .replace(/true/gi, "1")
            .replace(/false/gi, "0")

isn't going to work because MyVariableIsTrue will become MyVariableIs1, whereas the \b method won't convert the x==true?a:b part

How can I do regex this so it will match "whole word" instances of true and false (case independently) ? thanks

user2728841
  • 1,333
  • 17
  • 32
  • 1
    I think [`.replace(/(^|\W)true(?!\w)/g, '$11')`](http://jsfiddle.net/r2rcr0aw/1/) should work in all contexts. – Wiktor Stribiżew Dec 03 '15 at 10:30
  • Both this and the accepted solution seem to work. I'm kind of in disbelief that the accepted solution did work, but the above seems safer, logically, maybe !! thank you – user2728841 Dec 03 '15 at 12:04
  • `/\btrue\b/gi` will work unless you add any non-word before or after `true`, like `/\b=true\b/g`. I did not post my solution as I got baffled by your *`\b` method won't convert...* and vks posted that very solution. It only proves the point you did some mistake during your testing, and the question was asked due to some typo. – Wiktor Stribiżew Dec 03 '15 at 12:06

1 Answers1

2
   return expr
    .replace(/\btrue\b/gi, "1")
    .replace(/\bfalse\b/gi, "0")

Use \b which is word boundary for the same.

vks
  • 67,027
  • 10
  • 91
  • 124