[英]How can I remove all whitespace from a string except when part of said string is surrounded by a specific character in Node?
Say we have this string:假设我们有这个字符串:
this is an example: 'this is too'
I need this output:我需要这个 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.如果有帮助,我在这里找到了这篇文章,但它在 python 中,我几乎不知道如何翻译。
If you're wondering, this is for a data parser.如果您想知道,这是针对数据解析器的。
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 (eg 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.基本上就像您提到的 python 一样,此代码拆分(使用.split() )字符串,然后迭代新数组并检查当前迭代的元素是否是应该删除空格的字符串的一部分(例如,首先索引为 [0]) 的元素不是
''
内字符串的一部分,检查由%
完成,如果不是,它将再次将其添加到''
中,最后我们.filter()数组和.join ()它的元素得到一个新的字符串。
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));
You can accomplish this behavior using the trim() method, the ternary operator & with this sexy one-liner:您可以使用trim()方法、 三元运算符& 和这个性感的单行符来完成此行为:
const trimString = str => str[0] == "'" ? str : str.trim()
trimString('\' John Snow \'')
trimString(' John Summer ')
Check this working code sample .检查此工作代码示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.