简体   繁体   English

如何使用 Javascript 切/切/修剪字符串中的最后一个字符?

[英]How do I chop/slice/trim off last character in string using Javascript?

I have a string, 12345.00 , and I would like it to return 12345.0 .我有一个字符串12345.00 ,我希望它返回12345.0

I have looked at trim , but it looks like it is only trimming whitespace and slice which I don't see how this would work.我看过trim ,但看起来它只是修剪空白和slice ,我看不出这是如何工作的。 Any suggestions?有什么建议?

You can use the substring function:您可以使用子字符串函数:

 let str = "12345.00"; str = str.substring(0, str.length - 1); console.log(str);

This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:这是公认的答案,但根据下面的对话, 切片语法要清晰得多:

 let str = "12345.00"; str = str.slice(0, -1); console.log(str);

You can use slice !您可以使用切片 You just have to make sure you know how to use it.你只需要确保你知道如何使用它。 Positive #s are relative to the beginning, negative numbers are relative to the end.正#s 相对于开头,负数相对于结尾。

js>"12345.00".slice(0,-1)
12345.0

You can use the substring method of JavaScript string objects:你可以使用 JavaScript 字符串对象的substring方法:

s = s.substring(0, s.length - 4)

It unconditionally removes the last four characters from string s .它无条件地从字符串s删除最后四个字符。

However, if you want to conditionally remove the last four characters, only if they are exactly _bar :但是,如果您想有条件地删除最后四个字符,则仅当它们恰好是_bar

var re = /_bar$/;
s.replace(re, "");

The easiest method is to use the slice method of the string, which allows negative positions (corresponding to offsets from the end of the string):最简单的方法是使用字符串的slice方法,它允许负位置(对应于从字符串末尾的偏移量):

const s = "your string";
const withoutLastFourChars = s.slice(0, -4);

If you needed something more general to remove everything after (and including) the last underscore, you could do the following (so long as s is guaranteed to contain at least one underscore):如果您需要更一般的东西来删除(包括)最后一个下划线之后的所有内容,您可以执行以下操作(只要s保证包含至少一个下划线):

 const s = "your_string"; const withoutLastChunk = s.slice(0, s.lastIndexOf("_")); console.log(withoutLastChunk);

For a number like your example, I would recommend doing this over substring :对于像您的示例这样的数字,我建议在substring执行此操作:

 console.log(parseFloat('12345.00').toFixed(1));

Do note that this will actually round the number, though, which I would imagine is desired but maybe not:请注意,这实际上会舍入这个数字,我认为这是需要的,但可能不是:

 console.log(parseFloat('12345.46').toFixed(1));

Using JavaScript's slice function:使用 JavaScript 的 slice 函数:

 let string = 'foo_bar'; string = string.slice(0, -4); // Slice off last four characters here console.log(string);

This could be used to remove '_bar' at end of a string, of any length.这可用于删除任何长度的字符串末尾的“_bar”。

A regular expression is what you are looking for:正则表达式就是您要查找的内容:

 let str = "foo_bar"; console.log(str.replace(/_bar$/, ""));

Try this:尝试这个:

 const myString = "Hello World!"; console.log(myString.slice(0, -1));

Be aware that String.prototype.{ split, slice, substr, substring } operate on UTF-16 encoded strings请注意String.prototype.{ split, slice, substr, substring }对 UTF-16 编码的字符串进行操作

None of the previous answers are Unicode-aware.以前的答案都不是 Unicode 感知的。 Strings are encoded as UTF-16 in most modern JavaScript engines, but higher Unicode code points require surrogate pairs , so older, pre-existing string methods operate on UTF-16 code units, not Unicode code points.在大多数现代 JavaScript 引擎中,字符串被编码为 UTF-16,但更高的 Unicode 代码点需要代理对,因此旧的、预先存在的字符串方法在 UTF-16 代码单元上运行,而不是 Unicode 代码点。 See: Do NOT use .split('') .请参阅:不要使用.split('')

 const string = "ẞ🦊"; console.log(string.slice(0, -1)); // "ẞ\?" console.log(string.substr(0, string.length - 1)); // "ẞ\?" console.log(string.substring(0, string.length - 1)); // "ẞ\?" console.log(string.replace(/.$/, "")); // "ẞ\?" console.log(string.match(/(.*).$/)[1]); // "ẞ\?" const utf16Chars = string.split(""); utf16Chars.pop(); console.log(utf16Chars.join("")); // "ẞ\?"

In addition, RegExp methods, as suggested in older answers, don't match line breaks at the end:此外,正如旧答案中所建议的那样, RegExp方法在末尾不匹配换行符:

 const string = "Hello, world!\\n"; console.log(string.replace(/.$/, "").endsWith("\\n")); // true console.log(string.match(/(.*).$/) === null); // true


Use the string iterator to iterate characters使用字符串迭代器来迭代字符

Unicode-aware code utilizes the string's iterator; Unicode 感知代码使用字符串的迭代器; see Array.from and ... spread .参见Array.from... spread string[Symbol.iterator] can be used (eg instead of string ) as well. string[Symbol.iterator]也可以使用(例如代替string )。

Also see How to split Unicode string to characters in JavaScript .另请参阅如何在 JavaScript 中将 Unicode 字符串拆分为字符

Examples:例子:

 const string = "ẞ🦊"; console.log(Array.from(string).slice(0, -1).join("")); // "ẞ" console.log([ ...string ].slice(0, -1).join("")); // "ẞ"

Use the s and u flags on a RegExpRegExp上使用su标志

The dotAll or s flag makes . dotAlls标志使. match line break characters, the unicode or u flag enables certain Unicode-related features.匹配换行符, unicodeu标志启用某些与 Unicode 相关的功能。 Note that, when using the u flag, you eliminate unnecessary identity escapes, as these are invalid in a u regex , eg \\[ is fine, as it would start a character class without the backslash, but \\: isn't, as it's a : with or without the backslash, so you need to remove the backslash.请注意,当使用u标志时,您可以消除不必要的身份转义,因为这些在u正则表达式中是无效的,例如\\[很好,因为它会启动一个没有反斜杠的字符类,但\\:不是,因为它是a :有或没有反斜杠,所以你需要删除反斜杠。

Examples:例子:

 const unicodeString = "ẞ🦊", lineBreakString = "Hello, world!\\n"; console.log(lineBreakString.replace(/.$/s, "").endsWith("\\n")); // false console.log(lineBreakString.match(/(.*).$/s) === null); // false console.log(unicodeString.replace(/.$/su, "")); // ẞ console.log(unicodeString.match(/(.*).$/su)[1]); // ẞ // Now `split` can be made Unicode-aware: const unicodeCharacterArray = unicodeString.split(/(?:)/su), lineBreakCharacterArray = lineBreakString.split(/(?:)/su); unicodeCharacterArray.pop(); lineBreakCharacterArray.pop(); console.log(unicodeCharacterArray.join("")); // "ẞ" console.log(lineBreakCharacterArray.join("").endsWith("\\n")); // false


Note that some graphemes consist of more than one code point, eg 🏳️‍🌈 which consists of the sequence 🏳 (U+1F3F3), VS16 (U+FE0F) , ZWJ (U+200D) , 🌈 (U+1F308).请注意,有些字素由多个码位组成,例如🏳️‍🌈 ,它由序列🏳 (U+1F3F3)、 VS16 (U+FE0F)ZWJ (U+200D)🌈 (U+1F308) 组成。 Here, even Array.from will split this into four “characters”.在这里,即使是Array.from也会将其拆分为四个“字符”。 Matching those is made easier with the RegExp set notation and properties of strings proposal .使用RegExp 集合表示法和字符串提案的属性可以更容易地匹配这些。

Use regex:使用正则表达式:

 let aStr = "12345.00"; aStr = aStr.replace(/.$/, ''); console.log(aStr);

How about:怎么样:

 let myString = "12345.00"; console.log(myString.substring(0, myString.length - 1));

  1. (.*), captures any character multiple times (.*),多次捕获任何字符

 console.log("a string".match(/(.*).$/)[1]);

  1. ., matches last character, in this case ., 匹配最后一个字符,在这种情况下

 console.log("a string".match(/(.*).$/));

  1. $, matches the end of the string $, 匹配字符串的结尾

 console.log("a string".match(/(.*).{2}$/)[1]);

I have a string, 12345.00 , and I would like it to return 12345.0 .我有一个字符串12345.00 ,我希望它返回12345.0

I have looked at trim , but it looks like it is only trimming whitespace and slice which I don't see how this would work.我已经看过trim ,但是看起来它只是在修剪空白和slice ,我看不到它如何工作。 Any suggestions?有什么建议么?

I have a string, 12345.00 , and I would like it to return 12345.0 .我有一个字符串12345.00 ,我希望它返回12345.0

I have looked at trim , but it looks like it is only trimming whitespace and slice which I don't see how this would work.我已经看过trim ,但是看起来它只是在修剪空白和slice ,我看不到它如何工作。 Any suggestions?有什么建议么?

Here is an alternative that i don't think i've seen in the other answers, just for fun.这是我认为我在其他答案中没有看到的替代方案,只是为了好玩。

 var strArr = "hello i'm a string".split(""); strArr.pop(); document.write(strArr.join(""));

Not as legible or simple as slice or substring but does allow you to play with the string using some nice array methods, so worth knowing.不像 slice 或 substring 那样清晰或简单,但确实允许您使用一些不错的数组方法来处理字符串,因此值得了解。

Performance表现

Today 2020.05.13 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6.今天 2020.05.13 我在 MacOs High Sierra v10.13.6 上的 Chrome v81.0、Safari v13.1 和 Firefox v76.0 上对选定的解决方案进行了测试。

Conclusions结论

  • the slice(0,-1) (D) is fast or fastest solution for short and long strings and it is recommended as fast cross-browser solution slice(0,-1) (D) 是短字符串和长字符串的快速或最快解决方案,推荐作为快速跨浏览器解决方案
  • solutions based on substring (C) and substr (E) are fast基于substring (C) 和substr (E) 的解决方案很快
  • solutions based on regular expressions (A,B) are slow/medium fast基于正则表达式 (A,B) 的解决方案慢/中快
  • solutions B, F and G are slow for long strings解决方案 B、F 和 G 对于长字符串很慢
  • solution F is slowest for short strings, G is slowest for long strings解决方案 F 对于短字符串最慢,G 对于长字符串最慢

在此处输入图片说明

Details细节

I perform two tests for solutions A , B , C , D , E( ext ), F , G(my)我对解决方案ABCD 、 E( ext )、 F 、 G(my) 进行了两次测试

  • for 8-char short string (from OP question) - you can run it HERE对于 8 个字符的短字符串(来自 OP 问题)-您可以在此处运行它
  • for 1M long string - you can run it HERE对于 1M 长的字符串 - 你可以在这里运行

Solutions are presented in below snippet解决方案显示在下面的代码段中

 function A(str) { return str.replace(/.$/, ''); } function B(str) { return str.match(/(.*).$/)[1]; } function C(str) { return str.substring(0, str.length - 1); } function D(str) { return str.slice(0, -1); } function E(str) { return str.substr(0, str.length - 1); } function F(str) { let s= str.split(""); s.pop(); return s.join(""); } function G(str) { let s=''; for(let i=0; i<str.length-1; i++) s+=str[i]; return s; } // --------- // TEST // --------- let log = (f)=>console.log(`${f.name}: ${f("12345.00")}`); [A,B,C,D,E,F,G].map(f=>log(f));
 This snippet only presents soutions

Here are example results for Chrome for short string以下是 Chrome 短字符串的示例结果

在此处输入图片说明

debris = string.split("_") //explode string into array of strings indexed by "_"

debris.pop(); //pop last element off the array (which you didn't want)

result = debris.join("_"); //fuse the remainng items together like the sun

If you want to do generic rounding of floats, instead of just trimming the last character:如果您想对浮点数进行通用舍入,而不仅仅是修剪最后一个字符:

var float1 = 12345.00,
    float2 = 12345.4567,
    float3 = 12345.982;

var MoreMath = {
    /**
     * Rounds a value to the specified number of decimals
     * @param float value The value to be rounded
     * @param int nrDecimals The number of decimals to round value to
     * @return float value rounded to nrDecimals decimals
     */
    round: function (value, nrDecimals) {
        var x = nrDecimals > 0 ? 10 * parseInt(nrDecimals, 10) : 1;
        return Math.round(value * x) / x;
    }
}

MoreMath.round(float1, 1) => 12345.0
MoreMath.round(float2, 1) => 12345.5
MoreMath.round(float3, 1) => 12346.0

EDIT: Seems like there exists a built in function for this, as Paolo points out.编辑:正如 Paolo 指出的那样,似乎存在一个内置函数。 That solution is obviously much cleaner than mine.那个解决方案显然比我的要干净得多。 Use parseFloat followed by toFixed使用parseFloat后跟toFixed

if(str.substring(str.length - 4) == "_bar")
{
    str = str.substring(0, str.length - 4);
}

You can, in fact, remove the last arr.length - 2 items of an array using arr.length = 2 , which if the array length was 5, would remove the last 3 items.实际上,您可以使用arr.length = 2删除数组的最后arr.length - 2项,如果数组长度为 5,则将删除最后 3 项。

Sadly, this does not work for strings, but we can use split() to split the string, and then join() to join the string after we've made any modifications.遗憾的是,这不适用于字符串,但我们可以使用split()来拆分字符串,然后在我们进行任何修改后使用join()来连接字符串。

 var str = 'string' String.prototype.removeLast = function(n) { var string = this.split('') string.length = string.length - n return string.join('') } console.log(str.removeLast(3))

Via slice(indexStart, indexEnd) method - note, this does NOT CHANGE the existing string, it creates a copy and changes the copy.通过 slice(indexStart, indexEnd) 方法 - 请注意,这不会更改现有字符串,它会创建一个副本并更改副本。

console.clear();
let str = "12345.00";
let a = str.slice(0, str.length -1)
console.log(a, "<= a");
console.log(str, "<= str is NOT changed");

Via Regular Expression method - note, this does NOT CHANGE the existing string, it creates a copy and changes the copy.通过正则表达式方法 - 请注意,这不会更改现有字符串,它会创建一个副本并更改副本。

console.clear();
let regExp = /.$/g
let b = str.replace(regExp,"")
console.log(b, "<= b");
console.log(str, "<= str is NOT changed");

Via array.splice() method -> this only works on arrays, and it CHANGES, the existing array (so careful with this one), you'll need to convert a string to an array first, then back.通过 array.splice() 方法 -> 这仅适用于数组,并且它会更改现有数组(对这个数组非常小心),您需要先将字符串转换为数组,然后再返回。

console.clear();
let str = "12345.00";
let strToArray = str.split("")
console.log(strToArray, "<= strToArray");
let spliceMethod = strToArray.splice(str.length-1, 1)
str = strToArray.join("")
console.log(str, "<= str is changed now");

Try to use toFixed尝试使用toFixed

const str = "12345.00";
return (+str).toFixed(1);

In cases where you want to remove something that is close to the end of a string (in case of variable sized strings) you can combine slice() and substr().如果您想删除接近字符串末尾的内容(在可变大小字符串的情况下),您可以结合使用 slice() 和 substr()。

I had a string with markup, dynamically built, with a list of anchor tags separated by comma.我有一个带有标记的字符串,动态构建的,带有以逗号分隔的锚标记列表。 The string was something like:字符串是这样的:

var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";

To remove the last comma I did the following:要删除最后一个逗号,我执行了以下操作:

str = str.slice(0, -5) + str.substr(-4);

Try this:尝试这个:

<script>
    var x="foo_foo_foo_bar";
    for (var i=0; i<=x.length; i++) {
        if (x[i]=="_" && x[i+1]=="b") {
            break;
        }
        else {
            document.write(x[i]);
        }
    }
</script>

You can also try the live working example on http://jsfiddle.net/informativejavascript/F7WTn/87/ .您还可以尝试http://jsfiddle.net/informativejavascript/F7WTn/87/上的实时工作示例。

@Jason S: @杰森S:

You can use slice!你可以使用切片! You just have to make sure you know how to use it.你只需要确保你知道如何使用它。 Positive #s are relative to the beginning, negative numbers are relative to the end.正#s 相对于开头,负数相对于结尾。

js>"12345.00".slice(0,-1) 12345.0 js>"12345.00".slice(0,-1) 12345.0

Sorry for my graphomany but post was tagged 'jquery' earlier.抱歉我的笔墨,但帖子早些时候被标记为“jquery”。 So, you can't use slice() inside jQuery because slice() is jQuery method for operations with DOM elements, not substrings ... In other words answer @Jon Erickson suggest really perfect solution.所以,你不能在 jQuery 中使用slice()因为slice()是用于操作 DOM 元素的 jQuery 方法,而不是子字符串......换句话说,回答@Jon Erickson提出了非常完美的解决方案。

However, your method will works out of jQuery function, inside simple Javascript.但是,您的方法将在简单的 Javascript 中使用 jQuery 函数。 Need to say due to last discussion in comments, that jQuery is very much more often renewable extension of JS than his own parent most known ECMAScript.需要说明的是,由于评论中的最后一次讨论,jQuery 比他自己的父母最知名的 ECMAScript 更经常是 JS 的可更新扩展。

Here also exist two methods:这里也存在两种方法:

as our:作为我们的:

string.substring(from,to) as plus if 'to' index nulled returns the rest of string. string.substring(from,to) as plus 如果 'to' 索引为空,则返回字符串的其余部分。 so: string.substring(from) positive or negative ...所以: string.substring(from)正或负...

and some other - substr() - which provide range of substring and 'length' can be positive only: string.substr(start,length)和其他一些 - substr() - 提供子字符串范围和 'length' 只能是正数: string.substr(start,length)

Also some maintainers suggest that last method string.substr(start,length) do not works or work with error for MSIE.还有一些维护者建议最后一个方法string.substr(start,length)对 MSIE 不起作用或有错误。

Use substring to get everything to the left of _bar.使用 substring 获取 _bar 左侧的所有内容。 But first you have to get the instr of _bar in the string:但首先你必须在字符串中获取 _bar 的 instr:

str.substring(3, 7);

3 is that start and 7 is the length. 3 是起点,7 是长度。

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

相关问题 如何使用 JavaScript 选择字符串的最后一个字符? - How do I select the last character of a string, using JavaScript? 如何从字符串的开头和结尾剪掉特定字符? - How can I trim a specific character off the start & end of a string? 如果字符串javascript的最后一个字符如何摆脱? - How do I get rid if the last character of a string javascript? 如何在每个字符串之间用逗号分割数组? - How do i chop up an array with a comma between every string? 如何在JavaScript中的特定字符后修剪字符串 - How to trim a string after a specific character in javascript 切片,从特定字符修剪字符串 - Slice, trim the string from a specific character 我希望我的删除按钮删除字符串中的最后一个字符。 Substring 和切片在 javascript 中未按预期工作 - I want my delete button to remove last character in the string. Substring and slice not working as expected in javascript Javascript Slice:是否可以使用2个参数选择字符串的最后一个字符? - Javascript Slice: Is is possible to use 2 parameters to select the last character of a string? 如何使用javascript替换json字符串中的所有字符 - How do I replaceAll character from json string using javascript 如何在JavaScript中的字符串的最后两个字符之间替换一个字符? - How do I replace a character between the last occurrence of two characters in a string in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM