Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to remove not only spaces, but certain characters, as well from the beginning or end of a JavaScript string.

function trim(str, characters) {
  var c_array = characters.split('');
  var result  = '';

  for (var i=0; i < characters.length; i++)
    result += '\\' + c_array[i];

  return str.replace(new RegExp('^[' + result + ']+|['+ result +']+$', 'g'), '');
}

The function can be used as follows:

trim(' - hello**   +', '+*- ');

The escaping is required as + * . etc. would be used in the regular expression. Is there a better way to trim any character in JavaScript? Or a better way to do the escaping, as not every character needs it?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

There are many different ways to tackle trimming , a is probably the most popular, and there are lots of blogs and performance tests out there, (one such blog), that you can look at and decide which is best.

So continuing along the lines that you have demonstrated, then this may be of some help to you.

Javascript

/*jslint maxerr: 50, indent: 4, browser: true */

var trim = (function () {
    "use strict";

    function escapeRegex(string) {
        return string.replace(/[\[\](){}?*+\^$\\.|\-]/g, "\\$&");
    }

    return function trim(str, characters, flags) {
        flags = flags || "g";
        if (typeof str !== "string" || typeof characters !== "string" || typeof flags !== "string") {
            throw new TypeError("argument must be string");
        }

        if (!/^[gi]*$/.test(flags)) {
            throw new TypeError("Invalid flags supplied '" + flags.match(new RegExp("[^gi]*")) + "'");
        }

        characters = escapeRegex(characters);

        return str.replace(new RegExp("^[" + characters + "]+|[" + characters + "]+$", flags), '');
    };
}());

/*jslint devel: true */

console.log(trim(" - hello** +", "+*- "));

On jsfiddle

Of course, you can customise which characters you wish to escape, or flags to test for, as per your own needs. Regular Expressions

share|improve this answer
    
Good solution, but please use following function to determine if the parameter is a string: var isString = function(str) { return typeof str == 'string' || str instanceof String; }; If you try to use a string like this new String('123') it won't work... –  algorhythm May 6 at 8:52
    
If that was a concern then I would probably go for Object.prototype.toString.call(str) === '[object String]' as a safer option. –  Xotic750 May 6 at 14:52
<html>
<head>
    <script>
        function trimvalue(){
            var txt = document.getElementById('txt').value.trim();
            alert(txt);
        }
    </script>
</head>
<body>
    <form id="frm">
        <input type="text" name="txt" id="txt">
        <input type="button" onclick="trimvalue()" value="Click Me !">
    </form>
</body>
</html>
share|improve this answer
    
Hello, and welcome to code-review. As the name suggests, this site is geared more towards people giving actual advice and critiques concerning code quality, good practices and providing the info on what a particular snippet of code does, and why it could/should be improved on. Code-only answers are discouraged. Providing the code you think is better is great, but you should explain why your code is better. As it stands, this answer is not a good fit for this site. Please expand, or remove your answer –  Elias Van Ootegem Jun 24 at 11:12
    
Additionally, this code just trims space, whereas the original question was specifically trimming other content as well. –  rolfl Jun 24 at 11:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.