如何将字符串中的两个或多个空格转换为一个空格?JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/3 5:32:17
我们必须编写一个 JavaScript 程序,通过 HTML 中的输入获取变量用户字符串。然后通过 JavaScript,程序应该检查字符串中是否存在多个连续空格。
并且程序应该将所有此类多个连续空格的实例替换为一个空格。
我们可以使用正则表达式作为 replace 的第一个参数。/\s{2,}/g 来实现所需的结果。让我们为这个函数 − 编写代码
示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>删除空格</title>
</head>
<body>
<script>
function removeSpaces() {
var textInput = insertText.value;
var textInput = textInput.replace(/\s{2,}/g, " ");
insertText.value = textInput;
}
</script>
<input type="text" id="insertText" value="包含额外空格>
<button onclick="removeSpaces()>ok</button>
</body>
</html>
输出将是 −

单击"确定"后,

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

