简体   繁体   English

从 javascript 中的字符串中删除最后一个 & 的干净方法

[英]Clean way of removing last & from a string in javascript

Following is the code which is working fine for me, the only problem here I can see that I need to call slice(0, -1) on my string to remove & from the last.以下是对我来说工作正常的代码,这里唯一的问题是我需要在我的字符串上调用slice(0, -1)以从最后一个中删除& Let me know if there is a better and efficient way of writing this or this is also acceptable.让我知道是否有更好、更有效的方式来写这个或者这也是可以接受的。

Thanks in advance.提前致谢。

Code -代码 -

 const object1 = { a: 'somestring', b: 42, c: '', d: "test1", e: null, f: 'test2' }; let str = ''; for (const [key, value] of Object.entries(object1)) { str += `${key}=${value}&` } const paramStr = str.slice(0, -1); console.log(paramStr);

I think doing the slice is fine.我认为做slice很好。 There are numerous other ways you could approach not having it.还有许多其他方法可以让你接近没有它。 For example, you could map and then use .join('&') :例如,您可以map然后使用.join('&')

 const object1 = { a: 'somestring', b: 42, c: '', d: "test1", e: null, f: 'test2' }; console.log(Object.entries(object1).map(([k,v]) => `${k}=${v}`).join('&'))

Simply map and join , that will get rid of the trailing & :只需mapjoin ,这将摆脱尾随&

let paramStr = Object.entries(object1).map(([key, value]) => key + "=" + value).join("&");

Demo:演示:

 const object1 = { a: 'somestring', b: 42, c: '', d: "test1", e: null, f: 'test2' }; let paramStr = Object.entries(object1).map(([key, value]) => key + "=" + value).join("&"); console.log(paramStr);

If you are using lodash , you can consider utilizing the trimEnd function.如果您使用lodash ,可以考虑使用trimEnd function。

It can remove specified characters from the end of a string if you pass them as a second parameter.如果您将它们作为第二个参数传递,它可以从字符串的末尾删除指定的字符。

For example:例如:

 const paramStr = _.trimEnd('a=somestring&b=42&c=&d=test1&e=null&f=test2&', '&'); console.log(paramStr); // "a=somestring&b=42&c=&d=test1&e=null&f=test2"
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js"></script>

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

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