正则表达式jQuery无法正常工作

时间:2016-03-11 06:41:14

标签: javascript jquery regex

我在使用reg表达式删除标题中不需要的空格时遇到了一些问题。这是我的代码:

<ul>
 <li>
    <a href="#make/281">
      <img src="/images/cook-hat.svg">
      <span class="label label-primary">label</span>
      <div class="title-box"><span class="title">      my title     </span></div>
      <span class="goal-list">4</span>
    </a>
 </li>


$("li").val(
  $("span.title").text().replace(/\n/g, "")
  .replace(/\s/g,'')
);

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

  

使用.text()代替.val()

试试这个:

$("li").text(
  $("span.title").text().replace(/\n/g, "")
  .replace(/\s/g, ' ')
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
  <li>
    <a href="#make/281">
      <img src="/images/cook-hat.svg">
      <span class="label label-primary">label</span>
      <div class="title-box"><span class="title">      my title     </span>
      </div>
      <span class="goal-list">4</span>
    </a>
  </li>
</ul>

修改:设置多个li元素的文字。

$("li").text(
  function() {
    return $(this).find("span.title").text().replace(/\n/g, "")
      .replace(/\s/g, ' ')
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
  <li>
    <a href="#make/281">
      <img src="/images/cook-hat.svg">
      <span class="label label-primary">label</span>
      <div class="title-box"><span class="title">      my title     </span>
      </div>
      <span class="goal-list">4</span>
    </a>
  </li>
  <li>
    <a href="#make/281">
      <img src="/images/cook-hat.svg">
      <span class="label label-primary">label</span>
      <div class="title-box"><span class="title">      my title     </span>
      </div>
      <span class="goal-list">4</span>
    </a>
  </li>
</ul>

答案 1 :(得分:1)

  

.replace(/ \ S / G,&#39;&#39)

将替换文本中的所有空格。因为您说 int startRange = 1; int endRange = 10 ; String key; for(int i=startRange;i<=endRange;i++){ key = ""+i; Delete d=new Delete(Bytes.toBytes(key)); deleteList.add(d); } myTable.delete(deleteList); ,所以不确定是否要这样做。

如果要从跟随和尾随空格修剪字符串,只需执行

remove unwanted spaces