0

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?

1
  • let arr = "d d, b b, c c, d d ".trim().replace(/ /g,"_").split(","); Commented Nov 23, 2018 at 9:09

6 Answers 6

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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

Thanks for your help!
0

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

Thanks for your help!
It is something not related with this answer, but I think you can help me here stackoverflow.com/questions/53443925/…
0

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

Thanks for your help!
It is something not related with this answer, but I think you can help me here stackoverflow.com/questions/53443925/…
0

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

0

Trim and replace before splitting

console.log(
 "d d, b b, c c, d d ".trim().replace(/ /g,"_").split(",")
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.