verism
verism

Reputation: 1164

Regex match all spaces except those at the end of a string

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

Answers (2)

Amit Joki
Amit Joki

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

Avinash Raj
Avinash Raj

Reputation: 174706

You need to add $ inside the negative lookahead.

\s(?!$)

OR

 (?!$)

Upvotes: 1

Related Questions