0

Im building a query to submit to a search, one of the input fields is a filter for "OR". I need to replace whitespace with +OR+..only if the whitespace occurs outside of quoted text. So this is the logic:

"Happy Days"+OR+"Love Boat"

I have working code that will do that here:

var filter2=$('[name=filter2]').val();
var str2 = jQuery.trim(filter2);
var filter2d = str2.replace(/" "/g, "\"+OR+\"");

This only works if the text has quotes..I would like to be able to do this as well:

fonzy+OR+"Happy Days"+OR+"Love Boat"

Any help is appreciated

3 Answers 3

1

You can do it like this too.

'"abc def" ghi "klmno pqr"'.match(/"[^"]*"|[^\s]+/g).join("+OR+");
Sign up to request clarification or add additional context in comments.

Comments

1

Nailed it:

var input = '"abc def" ghi "klmno pqr" xyz';
input.replace (/("[^"]*"|\w+)(\s+|$)/g,'$1+OR+').slice (0,-4) ===
'"abc def"+OR+ghi+OR+"klmno pqr"+OR+xyz'

This assumes that your quoted strings contain no quote characters.

3 Comments

Darn, missed that extra +OR+in the final string
I would use [^"] instead of \w in case fon$y is valid.
Oh, also, I don't think you need to worry about trailing space because of var str2 = jQuery.trim(filter2);
0

This should do it...

function replaceWhiteSpace(str)
{
  insideAQuote = false;
  len = str.length
  for (i=0; i < len; i++)
  {
    if (str.charAt(i) == '"')
    {
      insideAQuote = !insideAQuote;
    }
    else if (str.charAt(i) == ' ' && !insideAQuote)
    {
      str = str.substr(0, i) + "+OR+" + str.substr(i+1);
    }
  }
  alert(str);
}

1 Comment

Looking back, I noticed your title said that you're looking for a regex... Oops, sorry. This will work regardless, and I bet it's faster too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.