简体   繁体   English

用于在javascript中忽略字符串的正则表达式

[英]Regular Expression for ignoring a string in javascript

Im building a query to submit to a search, one of the input fields is a filter for "OR". 我建立一个提交到搜索的查询,其中一个输入字段是“OR”的过滤器。 I need to replace whitespace with +OR+..only if the whitespace occurs outside of quoted text. 我需要用+ OR +替换空格..只有当空格出现在引用文本之外时。 So this is the logic: 所以这是逻辑:

"Happy Days"+OR+"Love Boat" “快乐的日子”+ OR +“爱情船”

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" fonzy + OR +“Happy Days”+ OR +“Love Boat”

Any help is appreciated 任何帮助表示赞赏

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. 这假定您引用的字符串不包含引号字符。

你也可以这样做。

'"abc def" ghi "klmno pqr"'.match(/"[^"]*"|[^\s]+/g).join("+OR+");

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM