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();
}
});
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.
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.
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.
Try with this:
.replace(/\s/g,"-");
Try this:
var str = 'a b c';
var replaced = str.split(' ').join('-');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With