前端将字符串去除全部空格, 每三个字符中间加个分号;
时间: 2024-04-13 22:30:51 浏览: 233
您可以使用以下 JavaScript 代码将字符串中的所有空格去除,并在每三个字符之间添加一个分号:
```javascript
function formatString(str) {
// 去除所有空格
str = str.replace(/\s/g, '');
// 在每三个字符之间添加分号
var formattedStr = '';
for (var i = 0; i < str.length; i += 3) {
formattedStr += str.slice(i, i + 3) + ';';
}
// 去除最后一个分号
formattedStr = formattedStr.slice(0, -1);
return formattedStr;
}
var input = "Hello World This is a Test";
var output = formatString(input);
console.log(output); // 输出: "Hel;loW;orl;dTh;isi;saT;est"
```
上述代码定义了一个 `formatString` 函数,它接受一个字符串作为参数,并返回格式化后的字符串。在函数内部,我们使用正则表达式 `\s` 匹配所有空格,并使用 `replace` 方法将其替换为空字符串。然后,我们使用 `for` 循环遍历字符串的每三个字符,并在它们之间添加一个分号。最后,我们使用 `slice` 方法去除最后一个分号,并返回格式化后的字符串。
相关问题
# 写一个python函数,输入一个字符串,把字符串中的逗号改为分号, # 原字符串的前后,或者字符串里逗号的前后有空格的话,要将空格去掉 # (但是如果两个逗号间只是空格,只保留一个空格),返回新的字符串。
你可以创建一个名为 `replace_comma_with_semicolon` 的 Python 函数,使用正则表达式来进行替换操作,并处理空格的情况。以下是函数实现的示例:
```python
import re
def replace_comma_with_semicolon(s):
# 使用正则表达式匹配逗号,如果前后有空格,则删除;如果有连续的空格,则保留一个
pattern = r'(?:^| )(\S*),(?:\s+|\S*$)'
# 替换逗号为分号,同时处理前后空格
new_string = re.sub(pattern, r'\1; ', s).strip()
return new_string
# 测试函数
original_str = "这是一个,测试字符串,前后有空格, 或者两个逗号间只有一个空格"
new_str = replace_comma_with_semicolon(original_str)
print(new_str)
```
在这个函数中,`re.sub()` 函数用于查找并替换匹配到的模式。`\1` 表示第一个捕获组的内容(即前面的非空白字符),`; ` 代表替换为分号后加一个空格。`strip()` 函数用于移除字符串两端的多余空格。
python删除字符串中分号后的空格
可以使用字符串的split()方法将字符串按照分号进行切割,然后再删除每个切割出的字符串中的空格。具体实现如下:
```
s = "hello ; world ; python ; ; java ;"
items = s.split(";")
result = ""
for item in items:
item = item.strip() # 删除空格
if item:
result += item + ";"
print(result[:-1]) # 去掉最后一个分号
```
输出结果为:
```
hello;world;python;java
```
阅读全文
相关推荐
















