2016-03-11 24 views
0

我在使用reg表達式去除標題中不需要的空格時遇到了一些問題。這是我的代碼:正則表達式jQuery不工作

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

任何幫助,將不勝感激

+0

的'只有測試的'應及時更換或整個'li'元素? – Rayon

+0

我相信'li沒有價值'爲什麼要使用'.val()'?使用'.text()'或'.html()'根據需要 – guradio

+0

它工作原因是什麼問題? – guradio

回答

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>

+0

這很好,如果我想要通過多個li列表?我應該使用循環嗎? –

+0

是...使用'.each' – Rayon

+0

這是正確的嗎? (/ \ s/g,0)(「/」)/ '') }); –

1

.replace(/ \ S/G, '')

將替換文本中的所有空格。不知道你想要的,因爲你說remove unwanted spaces

如果要修剪從以下和尾隨空格的字符串,然後簡單地做

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

'/ g'匹配所有的事件 – Rayon

+0

'val()'爲'li'元素工作嗎? – Rayon

+0

@RayonDabre你是對的,它不會。更新了代碼 – gurvinder372