Joseph Zammit
Joseph Zammit

Reputation: 373

Regular expression jQuery not working

I'm having some problems using reg expression to remove unwanted spaces in my title. This is my code:

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

Any help would be appreciated

Upvotes: 0

Views: 35

Answers (2)

Rayon
Rayon

Reputation: 36609

Use .text() instead of .val()

Try this:

$("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>

Edit: To set text of multiple li elements.

$("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>

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

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

will replace all spaces in the text. Not sure you want that since you said remove unwanted spaces.

If you want to trim the string from following and trailing spaces, then simply do

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

Upvotes: 1

Related Questions