diff --git a/mysql-test/r/func_str.result b/mysql-test/r/func_str.result
index 12c1cf78f7cead5df6f8c77325146e8f9ed1037d..b4d1be5bd54de7b7c278f291f4f327e7755aa1ad 100644
--- a/mysql-test/r/func_str.result
+++ b/mysql-test/r/func_str.result
@@ -282,3 +282,9 @@ NULL	NULL	1	1	n
 two	'two'	0	0	'two'
 four	'four'	0	0	'four'
 drop table t1;
+select trim(trailing 'foo' from 'foo');
+trim(trailing 'foo' from 'foo')
+
+select trim(leading 'foo' from 'foo');
+trim(leading 'foo' from 'foo')
+
diff --git a/mysql-test/t/func_str.test b/mysql-test/t/func_str.test
index 9b0c076f23e203aa801c96bcbc33e987fe9a0472..ba6a8b55236e3370ee03cd84fa526038eb5811c1 100644
--- a/mysql-test/t/func_str.test
+++ b/mysql-test/t/func_str.test
@@ -172,3 +172,10 @@ create table t1(a char(4));
 insert into t1 values ('one'),(NULL),('two'),('four');
 select a, quote(a), isnull(quote(a)), quote(a) is null, ifnull(quote(a), 'n') from t1;
 drop table t1;
+
+#
+# Bug #5498: TRIM fails with LEADING or TRAILING if remstr = str
+#
+
+select trim(trailing 'foo' from 'foo');
+select trim(leading 'foo' from 'foo');
diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc
index 5d017b3a27ac5cd0f81b18e2a105514e089178be..9248cbc021706b4980d649a17eef13965ec120bb 100644
--- a/sql/item_strfunc.cc
+++ b/sql/item_strfunc.cc
@@ -1135,7 +1135,7 @@ String *Item_func_ltrim::val_str(String *str)
   {
     const char *r_ptr=remove_str->ptr();
     end-=remove_length;
-    while (ptr < end && !memcmp(ptr,r_ptr,remove_length))
+    while (ptr <= end && !memcmp(ptr, r_ptr, remove_length))
       ptr+=remove_length;
     end+=remove_length;
   }
@@ -1206,8 +1206,8 @@ String *Item_func_rtrim::val_str(String *str)
     else
 #endif /* USE_MB */
     {
-      while (ptr + remove_length < end &&
-	     !memcmp(end-remove_length,r_ptr,remove_length))
+      while (ptr + remove_length <= end &&
+	     !memcmp(end-remove_length, r_ptr, remove_length))
 	end-=remove_length;
     }
   }