0

I would like to replace each abbreviation like this: e.g.. That means one character, one dot, one character and one dot. Leading and trailing space. But this is not working:

str.replace(new RegExp('\s([A-z]\.[A-z]\.)\s', 'g'), 'abbreviation<$1>')

Example

Lorem e.g. ipsum

Should get

Lorem abbreviation<e.g.> ipsum
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • 1
    `[A-z]` doesn't match what you think: the ASCII range from uppercase letters to lowercase includes some non-letter characters too. Try `[A-Za-z]`, or the ignore case option. – Brian Stephens Dec 09 '16 at 18:31

3 Answers3

2

[A-z] doesn't match what you think: the ASCII range from uppercase letters to lowercase includes some non-letter characters too. Try [A-Za-z], or the ignore case option:

console.log("Lorem e.g. ipsum".replace(/\s([a-z]\.[a-z]\.)\s/gi, ' abbreviation<$1> '))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Brian Stephens
  • 5,161
  • 19
  • 25
0

in new Regexp syntax the string argument should have escaped slashes.

str.replace(new RegExp('\\s([A-Za-z]\\.[A-Za-z]\\.)\\s', 'g'), ' abbreviation<$1>')
Sagi_Avinash_Varma
  • 1,489
  • 11
  • 23
  • @mplungjan [A-z] is equivalent to [A-Za-z] as they form a continuos ASCII charecter range. Thats why it worked for me when i tested. notice that the z is small letter – Sagi_Avinash_Varma Dec 09 '16 at 18:35
  • See [*Why is this regex allowing a caret?*](http://stackoverflow.com/a/29771926/3832970) – Wiktor Stribiżew Dec 09 '16 at 18:36
  • @Sagi_Avinash_Varma: please check ASCII codes 91-96! Even if it happens to match this particular case, you should never use `[A-Za-z]` to match letters only. – Brian Stephens Dec 09 '16 at 18:36
0

Sounds like you want to do a bunch, so I'd define an array of objects like this.

var str = 'The FBI and NASA work for the US government'
var abbr = [
    { 
        short: 'FBI',
        long: 'Federal Bureau of Investigation'
    },
    { 
        short: 'NASA',
        long: 'National Aeronautics and Space Administration'
    },
    {
        short: 'US',
        long: 'United States'
    }
];

Then loop over them and replace like this:

for (var a = 0; a < abbr.length; a++) {
    str = str.replace(abbr[a].short, abbr[a].short + ' (' + abbr[a].long + ')');
}

Then you can console.log(str) and you get

FBI (Federal Bureau of Investigation) and NASA (National Aeronautics and Space Administration) work for the US (United States) government
Jack
  • 804
  • 7
  • 18