jQuery,如果包含X,那么这样做,但是有条件的吗?

时间:2014-11-13 10:17:10

标签: jquery

我有一个数据库填充的行,根据输入的内容需要不同的格式。有三种格式:

线示例1)$ 3.00
线示例1)每人两个$ 4.95
线示例2)小$ 5.00 |中等$ 10.00 |大$ 15.00

第1行)无需更改
第2行)需要在$
之前插入额外的空格 第3行)需要在|之前和之后插入额外的空格但不是在$(所有情况)之前

我环顾四周,试图将事情拼凑在一起,但却无法得到它。以下是我到目前为止的情况:



      $('.menu-price-value:contains("$")').each(function() {
        var newText = $(this).html().replace('$', '<span class="space"></span>$');
        $(this).html(newText);
      });

      $('.menu-price-value:contains("|")').each(function() {
        var newText = $(this).html().replace("|", "&nbsp;|&nbsp;");
        $(this).html(newText);
        $('.menu-price-value').addClass('remove-space');
      });
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

使用regexp查找所需的模式,然后使用字符串:

function myparser(text){    
    if (matches=text.match(/^([^|$])+\$(\d+(\.\d+))$/i))
        return matches[1]+"&nbsp;$"+matches[2];
    else if (text.match(/\|/))
    {
        var myArray=text.split("|");
        var toReturn="";
        for (var i in myArray)
        {
            toReturn+=myArray[i]+"&nbsp;"+"|"+"&nbsp;";
        }
        return toReturn;
    }
    else
        return text;
}

该函数检测字符串的类型,然后将其恢复为固定。

看到它起作用: 的 FIDDLE

答案 1 :(得分:0)

有一些问题

  • Javascript字符串replace仅替换第一场比赛(我知道比较蹩脚)。使用带有g(全局)选项的正则表达式替换所有出现。
  • 您在第二个示例(不仅仅是当前匹配)
  • 中定位了所有匹配的类

JSFiddle:http://jsfiddle.net/TrueBlueAussie/evn91m7y/1/

  $('.menu-price-value:contains(" $")').html(function () {
      return $(this).html().replace(/\$/g, '<span class="space">                                             </span>$');
  });

  $('.menu-price-value:contains("|")').html(function () {
      return $(this).html().replace(/\|/g, "&nbsp;|&nbsp;");
  }).addClass('remove-space');

为避免对$个匹配项进行|检查,您可以像这样添加:not(contains("|"))

  $('.menu-price-value:contains(" $"):not(:contains("|"))').html(function () {
      return $(this).html().replace(/\$/g, '<span class="space">                                             </span>$');
  });

e.g。 http://jsfiddle.net/TrueBlueAussie/evn91m7y/2/

甚至只需将.not() html()的检查顺序和选择器反转:http://jsfiddle.net/TrueBlueAussie/evn91m7y/4/

注释:

  • 您可以使用$的函数,该函数将html替换为每个元素的返回值。
  • 我区分了第一个例子和其他例子,其他例子在$之前有一个空格。另一种方法是查看值 space开头的值。
  • 我必须添加一些样式才能使{{1}}范围可见。
  • 我用造型夸大了这些变化,因此你可以更容易地看到它们。