Home > database >  Clean up white space in middle of text
Clean up white space in middle of text

Time:10-07

I've read quite a few different posts related to cleaning up text at the end, and a few that talk about cleaning in the middle, but none seem to work for me. Here's what I'm trying to do:

I've got an alert on a home page that will display an alert message. From there I'll capture the message and pass it into a separate value ( the separate value isn't important though).

<div class="globalAlert-text col-md-12 col-xs-12">
    <div class="alert-left" style="width: 100%;">
        <span class="alert-left-body">
          <strong>My App Update : </strong>
          <span class="alert-desc">
            If you’re unable to access the mobile app, please visit the Apple App Store (for iOS) or Google Play (for Android) and update the app on your mobile device.

          </span>
          <span class="notification-desc  " style="display: inline;">
            If you’re unable to access the mobile app, please visit the Apple App Store (for iOS) or Google Play (for Android) and update the app on your mobile device.

          </span>
         </span>
     </div>
     <div class="cta-link">
                                         </div>
</div>

From there I'm trying to use jQuery to capture the alert message using one of the following:

jQuery('.globalAlert-text').text().trim(str.replace(/[\t\n] /g,' '))
jQuery('.globalAlert-text').text().trim(str.split(/\s/).join(' '))

Both return the following:

'My App Update : \n\t\t\t\t\t \n\t\t\t\t\t\tIf you’re unable to access the mobile app, please visit the Apple App Store (for iOS) or Google Play (for Android) and update the app on your mobile device.\n\n\t\t\t\t\t \n\t\t\t\t\t \n\t\t\t\t\t\tIf you’re unable to access the mobile app, please visit the Apple App Store (for iOS) or Google Play (for Android) and update the app on your mobile device.'

I've been racking my brain on this and can't seem to figure out a good way to clean this up. Is there something I'm missing here?

Thanks for the help!!

CodePudding user response:

The argument that you pass to trim() is just ignored. See documentation trim doesn't need any arguments: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

Also trim() remove spaces only from star and end of line, not from the middle.

If you want to "deep trim" (remove double spaces to single space) you can try to do replace by regex. Like that:

const trimmed = jQuery('.globalAlert-text').text().trim().replace(/\s{2,}/g,' '))
  • Related