简体   繁体   中英

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. 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. There are numerous other ways you could approach not having it. For example, you could map and then use .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 & :

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.

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>

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