responseText contains extra whitespace characters (new lines, line feeds), how to prevent and remove them?

前端 未结 6 559
忘了有多久
忘了有多久 2021-01-03 13:17

I have an ajax script that calls a php file.

The php file echos \"yes\" or \"no\", I want to use the strings to do logical comparisons.

In the javascript,

6条回答
  •  清歌不尽
    2021-01-03 13:42

    I know you asked about doing the comparison without regexes, but given the conditions you mentioned above, that's going to be a very quick and effective way to get your answer, and won't necessarily perturb any other processing.

    var trimmedResponse = responseText.replace(/^\s*/,'').replace(/\s*$/,'').toLowerCase();
    if (trimmedResponse == 'yes') {
      // do your 'yes' case
    } else if (trimmedResponse == 'no') {
      // do your 'no' case
    } else {
      // do your 'none of the above' case
    }
    

    That's going to trim off leading white space, trailing white space (including the CR/LF combo), and convert to lower case just for comparison.

提交回复
热议问题