最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular expression for whitespace and quotes - Stack Overflow

programmeradmin4浏览0评论

I have read some of the other tutorials on here about regular expressions, but I am still having trouble creating exactly what I need.

I have an onblur function that does this...

var x = $("#outputpathid").val();     
var testwhitespace = new RegExp(/\s/g);
var testdoublequotes = new RegExp(/^\"|\"$/);

if (testwhitespace.test(x) && !testdoublequotes.test(x)) {
            $("#outputPathDivWhitespace").dialog({
                title: 'Output Path contains whitespace. Click the \'Close\' button to add quotes.',
                width: 500,
                modal: true,
                resizable: false,
                buttons: {
                'Close': function() {
                        $("#outputpathid").val('"'+x+'"');
                        $(this).dialog('close');
                    }
                }
            });
        }

...I want the function to test whether x, an input field string, contains a whitespace. If it does, also check to see if there are quotes. If there are NOT quotes and it contains a space, then add quotes around the entire string. This works fine until the string has either a beginning or end quote.

I am looking for some type of 'and' operator to replace the pipe in the testdoublequotes var. I found that I should be using the '?', but can not get it to work.

Can some please help? If you provide an answer, please explain exactly what you did so I can understand what is going on. Thanks!

I have read some of the other tutorials on here about regular expressions, but I am still having trouble creating exactly what I need.

I have an onblur function that does this...

var x = $("#outputpathid").val();     
var testwhitespace = new RegExp(/\s/g);
var testdoublequotes = new RegExp(/^\"|\"$/);

if (testwhitespace.test(x) && !testdoublequotes.test(x)) {
            $("#outputPathDivWhitespace").dialog({
                title: 'Output Path contains whitespace. Click the \'Close\' button to add quotes.',
                width: 500,
                modal: true,
                resizable: false,
                buttons: {
                'Close': function() {
                        $("#outputpathid").val('"'+x+'"');
                        $(this).dialog('close');
                    }
                }
            });
        }

...I want the function to test whether x, an input field string, contains a whitespace. If it does, also check to see if there are quotes. If there are NOT quotes and it contains a space, then add quotes around the entire string. This works fine until the string has either a beginning or end quote.

I am looking for some type of 'and' operator to replace the pipe in the testdoublequotes var. I found that I should be using the '?', but can not get it to work.

Can some please help? If you provide an answer, please explain exactly what you did so I can understand what is going on. Thanks!

Share Improve this question edited Jan 3, 2011 at 17:57 Bill the Lizard 406k212 gold badges574 silver badges892 bronze badges asked Jan 3, 2011 at 17:25 Mr. AntMr. Ant 7002 gold badges15 silver badges32 bronze badges 4
  • Am I right to say that something like foo bar" is to be changed to "foo bar" (and likewise for an opening quote)? – BoltClock Commented Jan 3, 2011 at 17:28
  • Yes... (need at least 15 char's for a ment) – Mr. Ant Commented Jan 3, 2011 at 17:34
  • And what about my "dog" has fleas should that be "my \"dog\" has fleas" In other words: do you need to escape quotes inside the string? – Hemlock Commented Jan 3, 2011 at 17:47
  • I doubt I will have to worry about quotes inside of the string since the string is a path to a directory. – Mr. Ant Commented Jan 3, 2011 at 17:50
Add a ment  | 

4 Answers 4

Reset to default 3
/^".*"$/

Use .* to match <anything> in between the double quotes. . matches any character, and * matches any number of the proceeding whatever. So .* matches any number of any character.

The double quotes don't need to be escaped, by the way. I removed the backslashes.

Here's a revised answer based on your ments. I think it does what you need since it deals with missing quotes too.

function q(str) {
  return (/\s/g).test(str) 
    ? str.replace(/^"?(.*?)"?$/, function(str, value) {
        return '"' + value + '"';
      })
    : str;
}

DEMO: http://jsbin./apeva3/edit

Explanation:

Pass it a string and it will add the double quotes as needed

  1. If the string has whitespace (/\s/g).test
  2. Replace everything that is not a starting " or and ending "
    • replace can take a lambda function, it passes the whole matched string and then each group function(str /*whole string*/, value /* group 1 */)
    • the string is replaced by whatever the lambda returns
    • in this case the replace returns whatever isn't in quotes surrounded by quotes

Old Answer

Your whitespace test looks good. For quotes try this:

/^(['"])​​​​​​​​​​​​​​.*?\1$/​​​​​​​​​​​​​​​​​

Here is how it works:

  1. If the first character is ' or " match it and remember the value ^(['"])
  2. Now match any number of characters non-greedily .*?
  3. Then match what was remembered before \1
  4. And the end of the line $

I think the problem is with this line: var testdoublequotes = new RegExp(/^\"|\"$/); What you're testing is if it begins OR ends with a double quote but you want to know if it has one on both sides (ie. begins AND ends with a double quote). In this case you can use .* to find anything between the quotes like so:

var testdoublequotes = new RegExp(/^\".*\"$/);

Here's what I would have done: http://www.jsfiddle/bradchristie/UhwWw/
(Second version with quote escaping: http://www.jsfiddle/bradchristie/UhwWw/2/ )

Cod demonstrated below:

<input type="text" id="x" /><br />
<span id="x-modified"></span>

and the JS:

var whiteSpace = /\s/;
var quotes = /^\x22?(.*?)\x22?$/;
$('#x').change(function(){
    // First grab the value inside the field
    var xValue = $(this).val();

    // next, check for whitespace
    if (whiteSpace.test(xValue)){
        // there is white space. So now check for quotes. If there are quotes
        // (either surrounded or on one side) grab only the value (less the
        // quotes) then re-surround it.
        var xTempValue = xValue.match(quotes)[1] || xValue;
        xValue = '"'+xTempValue+'"';
    }

    // dump the quoted value.
    $('#x-modified').text(xValue);
});
发布评论

评论列表(0)

  1. 暂无评论