Reputation: 49
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.
Upvotes: 2
Views: 61
Reputation: 11622
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));
Upvotes: 2
Reputation: 6382
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.
Upvotes: 1