Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery replace not replacing all spaces with -

Why is my jquery not replacing all spaces with a '-'. It only replaces the first space with a '-'

$('.modhForm').submit(function(event) {

        var $this = $(this),
            action = $this.attr('action'),
            query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value').

        if (action.length >= 2 && query.length >= 2 && query.lenght <=24) {

          // Use URI encoding
          var newAction = (action + '/' + query.replace(' ','-'));
          console.log('OK', newAction); // DEBUG

          // Change action attribute
          $this.attr('action', newAction);

        } else {
          console.log('To small to be any good'); // DEBUG

          // Do not submit the form
          event.preventDefault();
        }
    });
like image 530
Norman Avatar asked Jan 02 '13 11:01

Norman


People also ask

How do you replace all spaces?

Use the String. replaceAll() method to replace all spaces in a string, e.g. str. replaceAll(' ', '-'); . The replaceAll method will return a new string where all occurrences of a space have been replaced by the provided replacement.

How do I replace multiple spaces with one space?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do you replace spaces with dashes?

To replace the spaces with dashes in a string, call the replaceAll() method on the string, e.g. str. replaceAll(' ', '-') . The replaceAll method will return a new string where all spaces are replaced by dashes.


Video Answer


2 Answers

Try with this:

.replace(/\s/g,"-");

Demo: JSFiddle

like image 63
Vishal Suthar Avatar answered Sep 27 '22 18:09

Vishal Suthar


Try this:

var str = 'a b c';
var replaced = str.split(' ').join('-');
like image 23
Michel Ayres Avatar answered Sep 27 '22 18:09

Michel Ayres