整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

七爪源码:如何在 JavaScript 中的字符串字符之间添加空格

解如何在 JavaScript 中轻松地在字符串的字符之间添加空格。

在本文中,我们将学习如何在 JavaScript 中轻松地在字符串的字符之间包含空格。


1. String split() 和 Split join() 方法

要在字符串的字符之间添加空格,请在字符串上调用 split() 方法以获取字符数组,然后在数组上调用 join() 方法以使用空格分隔符连接字符。

例如:

function addSpace(str) {
  return str.split('').join(' ');
}const str1 = 'coffee';
const str2 = 'banana';console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a

String split() 方法使用指定的分隔符将字符串拆分为子字符串数组。

const str1 = 'coffee,milk,tea';
const str2 = 'sun-moon-star';console.log(str1.split(',')); // [ 'coffee', 'milk', 'tea' ]
console.log(str2.split('-')); // [ 'sun', 'moon', 'star' ]

通过使用空字符串 ('') 作为分隔符,我们将所有字符串字符拆分为单独的数组元素。

const str1 = 'coffee';
const str2 = 'banana';// Passing an empty string ('') to the split method// [ 'c', 'o', 'f', 'f', 'e', 'e' ]
console.log(str1.split(''));// [ 'b', 'a', 'n', 'a', 'n', 'a' ]
console.log(str2.split(''));

String join() 方法将数组中的每个字符串与分隔符组合在一起。 它返回一个包含连接数组元素的新字符串。

const arr = ['a', 'b', 'c', 'd'];console.log(arr.join(' ')); // a b c d
console.log(arr.join('-')); // a-b-c-d
console.log(arr.join('/')); // a/b/c/d

因此,将空格字符传递给 join() 会在结果串联中用空格分隔字符。

在某些情况下,字符串已经在某些字符之间包含空格。 在这种情况下,我们的方法会在字符之间添加更多空格。

function addSpace(str) {
  return str.split('').join(' ');
}// These strings have spaces between some characters
const str1 = 'co  ffee';
const str2 = 'bana  na';console.log(addSpace(str1)); // c o     f f e e
console.log(addSpace(str2)); // b a n a     n a

这是因为空格 (' ') 也是一个字符,就像一个字母,调用 split() 会使其成为数组中的一个单独元素,该元素将与其他空格组合。

// These strings have spaces between some characters
const str1 = 'co  ffee';
const str2 = 'bana  na';// The space characters are separate elements of the
// array from split()
/**
 * [
  'c', 'o', ' ',
  ' ', 'f', 'f',
  'e', 'e'
]
 */
console.log(str1.split(''));/**
 * [
  'b', 'a', 'n',
  'a', ' ', ' ',
  'n', 'a'
]
 */
console.log(str2.split(''));

如果我们想避免字符的多个间距,我们可以在 split() 和 join() 之间插入对 filter() 方法的调用。

function addSpace(str) {
  return str
    .split('')
    .filter((item) => item.trim())
    .join(' ');
}// The strings have spaces between some characters
const str1 = 'co  ffee';
const str2 = 'bana  na';console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a

Array filter() 方法返回一个新数组,该数组仅包含原始数组中的元素,传递给 filter() 的测试回调函数为其返回真值。 对空格 (' ') 调用 trim() 会产生一个空字符串 (''),这在 JavaScript 中不是真值。 因此,从 filter() 返回的结果数组中排除了空格。

小费

在 JavaScript 中,只有六个假值:false、null、undefined、0、''(空字符串)和 NaN。 其他所有值都是真实的。


2. for...of 循环

对于更命令式的方法,我们可以使用 JavaScript for...of 循环在字符串的字符之间添加一个空格。

function addSpace(str) {
  // Create a variable to store the eventual result
  let result = '';  for (const char of str) {
    // On each iteration, add the character and a space
    // to the variable
    result += char + ' ';
  }  // Remove the space from the last character
  return result.trimEnd();
}const str1 = 'coffee';
const str2 = 'banana';console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a

为了处理前面讨论的场景,其中字符串在某些字符之间有空格,请在每次迭代的字符上调用 trim(),并添加一个 if 检查以确保它是真实的,然后将它和空格添加到累积结果中:

function addSpace(str) {
  // Create a variable to store the eventual result
  let result = '';  for (const char of str) {
    // On each iteration, add the character and a space
    // to the variable    // If the character is a space, trim it to an empty
    // string, then only add it if it is truthy
    if (char.trim()) {
      result += char + ' ';
    }
  }  // Remove the space from the last character
  return result.trimEnd();
}const str1 = 'co  ffee';
const str2 = 'bana  na';console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a


关注七爪网,获取更多APP/小程序/网站源码资源!

.字符串replaceAll()方法

要在 JavaScript 中从字符串中删除所有空格,请在字符串上调用 replaceAll() 方法,将包含空格的字符串作为第一个参数传递,将空字符串 ('') 作为第二个参数传递。 例如, str.replaceAll(' ', '') 从 str 中删除所有空格。

const str = 'A B C';
const allSpacesRemoved = str.replaceAll(' ', '');console.log(allSpacesRemoved); // ABC

String replaceAll() 方法返回一个新字符串,其中模式的所有匹配项都被替换替换。 第一个参数是要匹配的模式,第二个参数是替换。 因此,将空字符串作为第二个参数传递会用空替换所有空格,从而将它们删除。

笔记

JavaScript 中的字符串是不可变的,replaceAll() 返回一个新字符串而不修改原始字符串。

const str = 'A B C';
const allSpacesRemoved = str.replaceAll(' ', '');console.log(allSpacesRemoved); // ABC// Original not modified
console.log(str); // A B C


2.字符串replace()方法和正则表达式

或者,我们可以通过调用字符串的 replace() 方法从字符串中删除所有空格,将匹配任何空格的正则表达式作为第一个参数传递,并将空字符串 ('') 作为第二个参数。

const str = 'A B C';
const allSpacesRemoved = str.replace(/ /g, '');console.log(allSpacesRemoved); // ABC

我们使用 g 正则表达式标志来指定字符串中的所有空格都应该匹配。 如果没有这个标志,只有第一个空格会被匹配和替换:

const str = 'A B C';// No 'g' flag in regex
const spacesRemoved = str.replace(/ /, '');// Only first space removed
console.log(spacesRemoved); // AB C

String replace() 方法返回一个新字符串,其中所有匹配项都替换为传递给它的第二个参数。 我们传递一个空字符串作为第二个参数,以将所有空格替换为空,从而将它们删除。

笔记

与 replaceAll() 一样,replace() 返回一个新字符串而不修改原始字符串。

const str = 'A B C';
const spacesRemoved = str.replace(/ /g, '');console.log(spacesRemoved); // ABC// Original not modified
console.log(str); // A B C

小费

我们指定的正则表达式只匹配字符串中的空格。 要匹配和删除所有空白字符(空格、制表符和换行符),我们必须使用不同的正则表达式:

const str = 'A B C \t D \n E';
const whitespaceRemoved = str.replace(/\s/g, '');console.log(whitespaceRemoved); // ABC


关注七爪网,获取更多APP/小程序/网站源码资源!

本篇文章主要给大家介绍PHP如何将post提交过来的数据进行空格过滤。

大家应该都知道,我们在开发登录界面时,除了前台的一些js验证,还有一些提交数据到后台后的验证。下面我就通过简单的代码示例,给大家介绍php后台过滤数据空格验证的方法。

1、login.html代码示例

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>登录</title>
 <style type="text/css">
 body {
 background: url(images/bg.png);
 }
 
 .login {
 width: 370px;
 margin: 100px auto 0px;
 text-align: center;
 }
 
 #username{
 width: 360px;
 height: 50px;
 border: none;
 background: #fff;
 border-radius: 10px;
 margin: 5px auto;
 padding-left: 10px;
 color: #745A74;
 font-size: 15px;
 }
 
 #password{
 width: 360px;
 height: 50px;
 border: none;
 background: #fff;
 border-radius: 10px;
 margin: 5px auto;
 padding-left: 10px;
 color: #745A74;
 font-size: 15px;
 }
 
 .botton {
 width: 130px;
 height: 40px;
 background: #745A74;
 border-radius: 10px;
 text-align: center;
 color: #fff;
 margin-top: 30px;
 line-height: 40px;
 }
 </style>
</head>
<body>
<div class="login">
 <form action="check1.php" method="post">
 <img src="images/header.png"><br>
 <input type="text" id="username" name="username" placeholder="请输入用户名!" value=""><br>
 <input type="password" id="password" name="password" placeholder="请输入密码!" value=""><br>
 <input type="submit" class="botton" onclick="add()" value="login">
 </form>
</div>
</body>
</html>

这里的form表单主要是通过post方式提交数据到check1.php中。

2、check1.php代码示例

<?php
$arr = ['admin'];
 
 
if (in_array(trim($_POST['username']),$arr)){
 echo "登录成功!";
}else{
 echo "用户名不存在!";
}
var_dump($_POST['username']);
var_dump(trim($_POST['username']));

前台登录界面效果如下图:

如果我们将上述check1.php代码中trim函数删除掉。

注:trim() 函数表示移除字符串两侧的空白字符或其他预定义字符。

那么当我们输入带空格的用户名,结果就如下图:

如图显示用户名不存在,这是由于我们后台没有进行过滤数据空格的操作。

当我们按照上述check1.php的完整代码来处理提交过来的数据,那么即使是带有空格的用户名,都会显示登录成功。

效果如下:

如图我们成功过滤了用户名前后的空格。

其实在我们日常登录各种后台的过程中,想必有一部分朋友都习惯在输入用户名或者密码时随手加空格。那么大家可以根据自身项目的需求,来决定是否需要进行过滤空格的操作。

本篇文章就是关于PHP将post提交过来的数据进行空格过滤的方法介绍,通俗易懂,希望对需要的朋友有所帮助!

注:本文转载来自PHP中文网,版权有PHP中文网独有,转载需注明出处,谢谢。