Reputation: 1164
On a keyup event in a text input field, I'm trying to replace any spaces with a hyphen, provided there follows another character; basically changing all spaces except for trailing spaces:
$('#id').val().replace(/ /g, '-'); // Currently targets *all* spaces
According to regexr, the following should work:
/[ ](?!\s)/g
But it doesn't work in practise, as evidenced by this fiddle.
What's the right approach to this problem, and why does regexr give me a false positive?
Upvotes: 0
Views: 47
Reputation: 59232
You can just capture trailing spaces and then attach it at last
$('#id').val(function(_,val){
var trailSpaces = val.match(/\s+$/g)[0];
return val.replace(/ /g,"-") + trailSpaces;
});
Upvotes: 0
Reputation: 174706
You need to add $
inside the negative lookahead.
\s(?!$)
OR
(?!$)
Upvotes: 1