So i am wondering how i can remove the space of last element in array.
Let's say i have a string:
let str = "d d, b b, c c, d d ";
let split = str.split(", ");
let arr = split.map(str => str.replace(/\s/g, '_'));
console.log(arr);
So as you can see i am chaining words inside array, but i have a problem that my last item in array have whitespace at the end which end with "_" at the end. How i can remove that space from the last element without removing the space between d d?
6 Answers 6
You can use String.prototype.trim().
The
trim()method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
let str = "d d, b b, c c, d d ";
let split = str.trim().split(", ");
let arr = split.map(str => str.replace(/\s/g, '_'));
console.log(arr);
Comments
Use str.trim() before replace():
let str = "d d, b b, c c, d d ";
let split = str.split(", ");
let arr = split.map(str => str.trim().replace(/\s/g, '_'));
console.log(arr);
1 Comment
One option would be to match word characters with a single space between them instead:
const str = "d d, b b, c c, d d ";
const strArr = str.match(/\w+ \w+/g)
const arr = strArr.map(str => str.replace(/\s/g, '_'));
console.log(arr);
2 Comments
You could trim the string before splitting.
let str = "d d, b b, c c, d d ";
let split = str.trim().split(", ");
let arr = split.map(str => str.replace(/\s/g, '_'));
console.log(arr);
2 Comments
trim white space using trim() it before splitting
let str = "d d, b b, c c, d d ";
let split = str.trim().split(", ");
let arr = split.map(str => str.replace(/\s/g, '_'));
console.log(arr);
Comments
Trim and replace before splitting
console.log(
"d d, b b, c c, d d ".trim().replace(/ /g,"_").split(",")
)
let arr = "d d, b b, c c, d d ".trim().replace(/ /g,"_").split(",");