Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Mar 2012
    Thanked 0 Times in 0 Posts

    In replace function how do you include a space along with character.

    Hi All,

    In the first replace below the 'a' is replaced with the 'b' which is fine, but if there is a need how do you include a space so that ' a' is replaced by the 'b'.

    When I try with the second code below every space in a line of text is replaced by the 'b' as I assume the replace sees the space as an independent position and replaces it with the 'b'

    I am using the a and b for example, although I am trying to replace/remove a space before a period with just the period. In effect if this were in the text...... 'I am a space .' it would become 'I am a space.'

    without the space....
    document.getElementById("xxx").value = document.getElementById("xxx").value.replace(/a/gi,'b');

    with a space....
    document.getElementById("xxx").value = document.getElementById("xxx").value.replace(/ a/gi,'b');


  2. #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Thanked 4,947 Times in 4,908 Posts
    The problem isn't the space, it's the period.

    Period is the WILDCARD character in regular expressions.

    So when you do .replace(/ ./gi,'') that says "replace every space that is followed by *ANY CHARACTER AT ALL*.

    Easy solution: "escape" the period to tell the regexp that you really *DO* want a period and only a period: .replace(/ \./gi,'')
    Be yourself. No one else is as qualified.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts