简体   繁体   中英

How to remove | Symbol from start and end

I tried the following code to remove | symbol from stand and end bus it does not work.

"|aabckdoio|".replace("/^\|/g","").replace("/\|$/","")

It would work, if you removed the double quotes from the regexes.

If you pass a string to .replace() it performs a normal string search and replace, not a regex search.

You can also combine the two .replace operations:

"|aabckdoio|".replace(/^\||\|$/g, "");

Also, if you know for certain that the | characters will always be there, you can do it without a regex at all:

"|aabckdoio|".slice(1, -1)

If you just have to remove first and last character you can use:

var str = "|aabckdoio|".slice(1, -1); 
str; // "aabckdoio"

Here is a possible solution for you, without using regexs. Uses String.indexOf , String.lastIndexOf and String.slice (could have used String.substring with slightly modified end index), but it only removes the start or end characters if they match the given arguments. Errors in arguments are quiet (except null or undefined ), and you may want them to be noisy and if so then just change the checking to suit your style/project.

Javascript

var testString1 = "|aabckdoio|",
    testString2 = "*|aabckdoio|*";

function trimChars(string, startCharacters /*, endCharacters */ ) {
    string = {}.valueOf.call(string).toString();
    startCharacters  = {}.valueOf.call(startCharacters).toString();

    var start = 0,
        end = string.length,
        startCharactersLength = startCharacters.length,
        endCharacters = startCharacters,
        endCharactersLength = startCharactersLength;

    if (arguments.length > 2) {
        endCharacters = {}.valueOf.call(arguments[2]).toString();
        endCharactersLength = endCharacters.length;
    }

    if (string.indexOf(startCharacters) === 0) {
        start = startCharactersLength;
    }

    if (string.lastIndexOf(endCharacters) === end - endCharactersLength) {
        end -= endCharactersLength;
    }

    return string.slice(start, end);
}

console.log(trimChars(testString1, "|"));
console.log(trimChars(testString2, "*|", "|*"));

output

aabckdoio
aabckdoio 

On jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM