2

Say we have this string:

this is an example: 'this is too'

I need this output:

thisisanexample:'this is too'

I need a method to be able to remove whitespace in a string except where any given section is surrounded by a character, in this case, '.

If it helps, I found this post here, but it's in python and I have just about no idea how to translate that.

If you're wondering, this is for a data parser.

jwpjr
  • 39
  • 6

2 Answers2

2

Basically just like the one you mentioned for python, this code split (using .split()) the string and then iterate over the new array and check if the current element iterated is part of the string that should have the spaces removed (e.g first element indexed [0]) is not part of the string inside '' and the check is done by %, and if its not it will add it again in '' and in the end it we .filter() the array and .join() its elements to get out a new string.

so I think this is what you want:

function splitStr(str) {
  let strArr = str.split("'");
  let newStr = "";
  strArr.forEach((el, i) => {
    if(i % 2 === 0) {
      strArr[i] = el.replace(/\s/g, '');
    }
    else {
      strArr[i] = `'${strArr[i]}'`;
    }
  })
  return strArr.filter(String).join('');
}

let str = "this is an example:'this is too'";
console.log(splitStr(str));
let str1 = "('test 2': 'the result' )";
console.log(splitStr(str1));

let str2 = "('test 2': the result )";
console.log(splitStr(str2));
ROOT
  • 11,363
  • 5
  • 30
  • 45
1

You can accomplish this behavior using the trim() method, the ternary operator & with this sexy one-liner:

const trimString = str => str[0] == "'" ? str : str.trim()

trimString('\'  John Snow  \'')
trimString('  John Summer ')

Check this working code sample.

Manuel Abascal
  • 5,616
  • 5
  • 35
  • 68
  • This is very useful but not exactly what I need. I need it to remove all whitespace except that in which is surrounded by said character (`'`), and this simply returns itself if it starts with `'`. – jwpjr Apr 09 '20 at 03:37
  • 1
    In this case, you'll need to turn the `string` into an `array` with the `split()` method, create `function` to remove the first & last characters & use `join()` method to turn the `array` into a `string` again. – Manuel Abascal Apr 09 '20 at 03:44