簡體   English   中英

正則表達式jQuery不起作用

[英]Regular expression jQuery not working

使用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,'')
);

任何幫助,將不勝感激

使用.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> 

.replace(/ \\ s / g,'')

將替換文本中的所有空格。 因為您說過要remove unwanted spaces ,所以不確定您是否remove unwanted spaces

如果您想從后面和后面的空格中修剪字符串,只需執行

$("li").html(  $("span.title").text().trim() );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM