Javascript 从字符串中修剪特定字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26156292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trim specific character from a string
提问by fubo
What's the JavaScriptequivalent to this C#Method:
与此方法等效的JavaScript是什么C#:
var x = "|f|oo||";
var y = x.Trim('|'); // "f|oo"
C# trims the selected character only at the beginningand endof the string!
C#只在字符串的开头和结尾修剪所选字符!
回答by leaf
One line is enough :
一行就够了:
var x = '|f|oo||';
var y = x.replace(/^\|+|\|+$/g, '');
document.write(x + '<br />' + y);
^\|+ beginning of the string, pipe, one or more times
| or
\|+$ pipe, one or more times, end of the string
In a function :
在一个函数中:
function trim (s, c) {
if (c === "]") c = "\]";
if (c === "\") c = "\\";
return s.replace(new RegExp(
"^[" + c + "]+|[" + c + "]+$", "g"
), "");
}
chars = ".|]\";
for (c of chars) {
s = c + "foo" + c + c + "oo" + c + c + c;
console.log(s, "->", trim(s, c));
}
回答by Pho3niX83
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:
如果我理解得很好,您只想删除位于字符串开头或结尾的特定字符(例如:||fo||oo||||应该变为foo||oo)。您可以创建一个临时函数,如下所示:
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, "|") + "'" );
回答by neelsg
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
回答by Robin F.
to keep this question up to date:
保持这个问题是最新的:
here is an approach i'd choose over the regex function using the ES6 spread operator.
这是我使用 ES6 扩展运算符选择 regex 函数的方法。
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);
}
回答by mbaer3000
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.
对于我们确定边缘字符没有重复的用例。
回答by Jason Larke
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');
回答by marlar
This can trim several characters at a time:
这可以一次修剪多个字符:
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
var y = "..++|f|oo||++..";
y = y.trimChars('|.+'); // f|oo
var z = "\f|oo\"; // \f|oo\
// For backslash, remember to double-escape:
z = z.trimChars("\\"); // f|oo
回答by Chris Redford
If you define these functions in your program, your strings will have an upgraded version of trimthat can trim all given characters:
如果你在你的程序中定义了这些函数,你的字符串将有一个升级版本trim,可以修剪所有给定的字符:
String.prototype.trimLeft = function(charlist) {
if (charlist === undefined)
charlist = "\s";
return this.replace(new RegExp("^[" + charlist + "]+"), "");
};
String.prototype.trim = function(charlist) {
return this.trimLeft(charlist).trimRight(charlist);
};
String.prototype.trimRight = function(charlist) {
if (charlist === undefined)
charlist = "\s";
return this.replace(new RegExp("[" + charlist + "]+$"), "");
};
var withChars = "/-center-/"
var withoutChars = withChars.trim("/-")
document.write(withoutChars)
Source
来源
回答by drew7721
I would suggest looking at lodash and how they implemented the trimfunction.
我建议查看 lodash 以及他们如何实现该trim功能。
See Lodash Trimfor the documentation and the sourceto see the exact code that does the trimming.
有关文档和源代码,请参阅Lodash Trim以查看进行修剪的确切代码。
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.
我知道这并没有提供您的问题的确切答案,但我认为在这样的问题上设置对图书馆的引用是很好的,因为其他人可能会发现它很有用。
回答by Dmitriy Botov
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

