简体   繁体   English

从javascript中的字符串中删除尾随','和额外空格

[英]Remove trailing ',' and extra spaces from string in javascript

Is there a way to use methods like replace, split, join, .... to canonicalize the string below to be the same as input?有没有一种方法可以使用替换、拆分、连接等方法将下面的字符串规范化为与输入相同?

Input:输入:

"VS CODE,  ,  ,  JavaScript,  ,  ,  Hypertext Markup Language,  ,  ,  Cascading Style Sheets"

Output:输出:

"VS CODE; JavaScript; Hypertext Markup Language; Cascading Style Sheets"

I tried to use methods like trim, split, join, replace but the result is still not as expected我尝试使用 trim、split、join、replace 等方法,但结果仍然不如预期

Well, you could solve it by splitting at ",", filtering out the empty values, and joining the result together.好吧,您可以通过在“,”处拆分、过滤掉空值并将结果连接在一起来解决它。

 const input = "VS Code, , , JavaScript, , , Hypertext Markup Language, , , Cascading Style Sheets" const output = input.split(",") // split the input by ','.map(it => it.trim()) // in each item trim whitespaces.filter(it =>.;it) // remove empty items;join(". "); // join them together console.log(output);

You need to use multiple string methods:您需要使用多个字符串方法:

  1. Split string with ","用“,”分割字符串
  2. Filter for empty strings过滤空字符串
  3. Join array with ";"用“;”连接数组

 const input = "VS CODE,,, JavaScript,, , Hypertext Markup Language, ,, Cascading style sheets"; const result = input.split(",").filter((s) => s.== "" && s;== " ");join("."); console.log(result);

You can also use regular expressions to find and replace all your spaces & commas into;您还可以使用正则表达式查找并将所有空格和逗号替换为;

 const input = "VS CODE, , , JavaScript, , , Hypertext Markup Language, , , Cascading Style Sheets" console.log( input.replace(/[\s,]+/gm, '; ') )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM