Gandalf
Gandalf

Reputation: 13693

jQuery trim function is not removing space at the end

I have some user input I am processing that removes special characters and replaces spaces with '+'. I am trimming from both ends of a string but maintaining the ones in between words so that they are replaced with +

$(document).on('submit','form.searchform',function(e){
        e.preventDefault();
        var st = $('#searchterm').val();
        st = st.trim();
        //st = st.replace(/\s+$/, '');
        st = st.replace(/[^a-zA-Z ]/g, "");
        st = st.replace(/\s+/g, '+');
        
        console.log(st);
});

and this is the fiddle with the result http://jsfiddle.net/9n6q4ms5/

This snippet:

var st = 'hello world this is a great thing #$@#$$%%^';
        st = st.trim();
        st = st.replace(/[^a-zA-Z ]/g, "");
        st = st.replace(/\s+/g, '+');
console.log(st);

produces:

"hello+world+this+is+a+great+thing+" which has a space at the end since it has a +.

What can i do to fix this?

Upvotes: 1

Views: 117

Answers (2)

Qaseem Saleem
Qaseem Saleem

Reputation: 90

Actually at the time of trim there were no space at the end, but after trim you replace the special character before which there were space. So you can re-arrange your code as shown in the snippet below:

var st = 'hello world this is a great thing #$@#$$%%^';
        st = st.replace(/[^a-zA-Z ]/g, "");
        st = st.trim();
        console.log(st);
        st = st.replace(/\s+/g, '+');
console.log(st);

Upvotes: 0

Tyr
Tyr

Reputation: 2810

The .trim() is on the wrong position. Your initial string has no space at the end. It's created after your first replace function. You have to move the .trim() call between the two:

var st = 'hello world this is a great thing #$@#$$%%^';
    st = st.replace(/[^a-zA-Z ]/g, "");
    st = st.trim();
    st = st.replace(/\s+/g, '+');
console.log(st);

Upvotes: 3

Related Questions