[javascript] Trim specific character from a string

What's the JavaScript equivalent to this C# Method:

var x = "|f|oo||"; 
var y = x.Trim('|'); //  "f|oo"

C# trims the selected character only at the beginning and end of the string!

This question is related to javascript string trim

The answer is


The best way to resolve this task is (similar with PHP trim function):

_x000D_
_x000D_
function trim( str, charlist ) {_x000D_
  if ( typeof charlist == 'undefined' ) {_x000D_
    charlist = '\\s';_x000D_
  }_x000D_
  _x000D_
  var pattern = '^[' + charlist + ']*(.*?)[' + charlist + ']*$';_x000D_
  _x000D_
  return str.replace( new RegExp( pattern ) , '$1' )_x000D_
}_x000D_
_x000D_
document.getElementById( 'run' ).onclick = function() {_x000D_
  document.getElementById( 'result' ).value = _x000D_
  trim( document.getElementById( 'input' ).value,_x000D_
  document.getElementById( 'charlist' ).value);_x000D_
}
_x000D_
<div>_x000D_
  <label for="input">Text to trim:</label><br>_x000D_
  <input id="input" type="text" placeholder="Text to trim" value="dfstextfsd"><br>_x000D_
  <label for="charlist">Charlist:</label><br>_x000D_
  <input id="charlist" type="text" placeholder="Charlist" value="dfs"><br>_x000D_
  <label for="result">Result:</label><br>_x000D_
  <input id="result" type="text" placeholder="Result" disabled><br>_x000D_
  <button type="button" id="run">Trim it!</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

P.S.: why i posted my answer, when most people already done it before? Because i found "the best" mistake in all of there answers: all used the '+' meta instead of '*', 'cause trim must remove chars IF THEY ARE IN START AND/OR END, but it return original string in else case.


_x000D_
_x000D_
const special = ':;"<>?/!`~@#$%^&*()+=-_ '.split("");
const trim = (input) => {
    const inTrim = (str) => {
        const spStr = str.split("");
        let deleteTill = 0;
        let startChar = spStr[deleteTill];
        while (special.some((s) => s === startChar)) {
            deleteTill++;
            if (deleteTill <= spStr.length) {
                startChar = spStr[deleteTill];
            } else {
                deleteTill--;
                break;
            }
        }
        spStr.splice(0, deleteTill);
        return spStr.join("");
    };
input = inTrim(input);
input = inTrim(input.split("").reverse().join("")).split("").reverse().join("");
return input;
};
alert(trim('@#This is what I use$%'));
_x000D_
_x000D_
_x000D_


String.prototype.TrimStart = function (n) {
    if (this.charAt(0) == n)
        return this.substr(1);
};

String.prototype.TrimEnd = function (n) {
    if (this.slice(-1) == n)
        return this.slice(0, -1);
};

If you define these functions in your program, your strings will have an upgraded version of trim that can trim all given characters:

_x000D_
_x000D_
String.prototype.trimLeft = function(charlist) {_x000D_
 if (charlist === undefined)_x000D_
 charlist = "\s";_x000D_
_x000D_
 return this.replace(new RegExp("^[" + charlist + "]+"), "");_x000D_
};_x000D_
_x000D_
String.prototype.trim = function(charlist) {_x000D_
 return this.trimLeft(charlist).trimRight(charlist);_x000D_
};_x000D_
_x000D_
String.prototype.trimRight = function(charlist) {_x000D_
 if (charlist === undefined)_x000D_
 charlist = "\s";_x000D_
_x000D_
 return this.replace(new RegExp("[" + charlist + "]+$"), "");_x000D_
};_x000D_
_x000D_
var withChars = "/-center-/"_x000D_
var withoutChars = withChars.trim("/-")_x000D_
document.write(withoutChars)
_x000D_
_x000D_
_x000D_

Source

https://www.sitepoint.com/trimming-strings-in-javascript/


expanding on @leaf 's answer, here's one that can take multiple characters:

var trim = function (s, t) {
  var tr, sr
  tr = t.split('').map(e => `\\\\${e}`).join('')
  sr = s.replace(new RegExp(`^[${tr}]+|[${tr}]+$`, 'g'), '')
  return sr
}

This one trims all leading and trailing delimeters

const trim = (str, delimiter) => {
  const pattern = `[^\\${delimiter}]`;
  const start = str.search(pattern);
  const stop = str.length - str.split('').reverse().join('').search(pattern);
  return str.substring(start, stop);
}

const test = '||2|aaaa12bb3ccc|||||';
console.log(trim(test, '|')); // 2|aaaa12bb3ccc

This can trim several characters at a time:

function trimChars (str, c) {
  var re = new RegExp("^[" + c + "]+|[" + c + "]+$", "g");
  return str.replace(re,"");
}

var x = "|f|oo||"; 
x =  trimChars(x, '|'); // f|oo

var y = "..++|f|oo||++..";
y = trimChars(y, '|.+'); // f|oo

var z = "\\f|oo\\"; // \f|oo\

// For backslash, remember to double-escape:
z = trimChars(z, "\\\\"); // f|oo

For use in your own script and if you don't mind changing the prototype, this can be a convenient "hack":

String.prototype.trimChars = function (c) {
  var re = new RegExp("^[" + c + "]+|[" + c + "]+$", "g");
  return this.replace(re,"");
}

var x = "|f|oo||"; 
x =  x.trimChars('|'); // f|oo

Since I use the trimChars function extensively in one of my scripts, I prefer this solution. But there are potential issues with modifying an object's prototype.


"|Howdy".replace(new RegExp("^\\|"),"");

(note the double escaping. \\ needed, to have an actually single slash in the string, that then leads to escaping of | in the regExp).

Only few characters need regExp-Escaping., among them the pipe operator.


To my knowledge, jQuery doesnt have a built in function the method your are asking about. With javascript however, you can just use replace to change the content of your string:

x.replace(/|/i, ""));

This will replace all occurences of | with nothing.


try:

console.log(x.replace(/\|/g,''));

I like the solution from @Pho3niX83...

Let's extend it with "word" instead of "char"...

function trimWord(_string, _word) {

    var splitted = _string.split(_word);

    while (splitted.length && splitted[0] === "") {
        splitted.shift();
    }
    while (splitted.length && splitted[splitted.length - 1] === "") {
        splitted.pop();
    }
    return splitted.join(_word);
};

I would suggest looking at lodash and how they implemented the trim function.

See Lodash Trim for the documentation and the source to see the exact code that does the trimming.

I know this does not provide an exact answer your question, but I think it's good to set a reference to a library on such a question since others might find it useful.


function trim(text, val) {
    return text.replace(new RegExp('^'+val+'+|'+val+'+$','g'), '');
}

to keep this question up to date:

here is an approach i'd choose over the regex function using the ES6 spread operator.

function trimByChar(string, character) {
  const first = [...string].findIndex(char => char !== character);
  const last = [...string].reverse().findIndex(char => char !== character);
  return string.substring(first, string.length - last);
}

Improved version after @fabian 's comment (can handle strings containing the same character only)

_x000D_
_x000D_
function trimByChar1(string, character) {
  const arr = Array.from(string);
  const first = arr.findIndex(char => char !== character);
  const last = arr.reverse().findIndex(char => char !== character);
  return (first === -1 && last === -1) ? '' : string.substring(first, string.length - last);
}
_x000D_
_x000D_
_x000D_


Try this method:

_x000D_
_x000D_
var a = "anan güzel mi?";_x000D_
if (a.endsWith("?"))   a = a.slice(0, -1);  _x000D_
document.body.innerHTML = a;
_x000D_
_x000D_
_x000D_


A regex-less version which is easy on the eye:

const trim = (str, chars) => str.split(chars).filter(Boolean).join(chars);

For use cases where we're certain that there's no repetition of the chars off the edges.


You can use a regular expression such as:

var x = "|f|oo||";
var y = x.replace(/^\|+|\|+$/g, "");
alert(y); // f|oo

UPDATE:

Should you wish to generalize this into a function, you can do the following:

var escapeRegExp = function(strToEscape) {
    // Escape special characters for use in a regular expression
    return strToEscape.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};

var trimChar = function(origString, charToTrim) {
    charToTrim = escapeRegExp(charToTrim);
    var regEx = new RegExp("^[" + charToTrim + "]+|[" + charToTrim + "]+$", "g");
    return origString.replace(regEx, "");
};

var x = "|f|oo||";
var y = trimChar(x, "|");
alert(y); // f|oo

If you're dealing with longer strings I believe this should outperform most of the other options by reducing the number of allocated strings to either zero or one:

function trim(str, ch) {
    var start = 0, 
        end = str.length;

    while(start < end && str[start] === ch)
        ++start;

    while(end > start && str[end - 1] === ch)
        --end;

    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}

// Usage:
trim('|hello|world|', '|'); // => 'hello|world'

Or if you want to trim from a set of multiple characters:

function trimAny(str, chars) {
    var start = 0, 
        end = str.length;

    while(start < end && chars.indexOf(str[start]) >= 0)
        ++start;

    while(end > start && chars.indexOf(str[end - 1]) >= 0)
        --end;

    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}

// Usage:
trimAny('|hello|world   ', [ '|', ' ' ]); // => 'hello|world'
// because '.indexOf' is used, you could also pass a string for the 2nd parameter:
trimAny('|hello| world  ', '| '); // => 'hello|world'

EDIT: For fun, trim words (rather than individual characters)

// Helper function to detect if a string contains another string
//     at a specific position. 
// Equivalent to using `str.indexOf(substr, pos) === pos` but *should* be more efficient on longer strings as it can exit early (needs benchmarks to back this up).
function hasSubstringAt(str, substr, pos) {
    var idx = 0, len = substr.length;

    for (var max = str.length; idx < len; ++idx) {
        if ((pos + idx) >= max || str[pos + idx] != substr[idx])
            break;
    }

    return idx === len;
}

function trimWord(str, word) {
    var start = 0,
        end = str.length,
        len = word.length;

    while (start < end && hasSubstringAt(str, word, start))
        start += word.length;

    while (end > start && hasSubstringAt(str, word, end - len))
        end -= word.length

    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}

// Usage:
trimWord('blahrealmessageblah', 'blah');

If I understood well, you want to remove a specific character only if it is at the beginning or at the end of the string (ex: ||fo||oo|||| should become foo||oo). You can create an ad hoc function as follows:

function trimChar(string, charToRemove) {
    while(string.charAt(0)==charToRemove) {
        string = string.substring(1);
    }

    while(string.charAt(string.length-1)==charToRemove) {
        string = string.substring(0,string.length-1);
    }

    return string;
}

I tested this function with the code below:

var str = "|f|oo||";
$( "#original" ).html( "Original String: '" + str + "'" );
$( "#trimmed" ).html( "Trimmed: '" + trimChar(str, "|") + "'" );

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to trim

How to remove whitespace from a string in typescript? Strip / trim all strings of a dataframe Best way to verify string is empty or null Does swift have a trim method on String? Trim specific character from a string Trim whitespace from a String Remove last specific character in a string c# How to delete specific characters from a string in Ruby? How to Remove the last char of String in C#? How to use a TRIM function in SQL Server