简体   繁体   English

如何删除 从开始到结束的符号

[英]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. 如果将字符串传递给.replace()它将执行普通的字符串搜索和替换,而不是正则表达式搜索。

You can also combine the two .replace operations: 您还可以将两个.replace操作结合使用:

"|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. 使用String.indexOfString.lastIndexOfString.slice (可以使用带有稍微修改的end索引的String.substring ),但是仅在匹配给定参数的开始或结束字符时才删除它们。 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. 参数中的错误是安静的( nullundefined除外),您可能希望它们嘈杂,如果是,则只需更改检查以适合您的样式/项目即可。

Javascript Java脚本

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 jsfiddle上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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