使用方法 includes() 检查字符串中是否出现数组中表示的字符返回 true - 从字符串中删除字符

using a method includes() checking string for occurrences of characters represented in array is returning true - removing characters from a string

我正在构建一个 URL slug 生成器,我需要的行为是如果输入的是:

Ok Now Let's Do This & See

输出需要

ok-now-lets-do-this-see

删除 &', 字符

let newStr;

function slugifyString(str) {
  let forbiddenChars = ["&", "'", ","];
    newStr = str.toLowerCase().replace(/\s/g, '-');
  if (newStr.includes(forbiddenChars) > -1) {
    console.log('a forbidden character is present')
  }
}

document.getElementById('slug-a-string-form').addEventListener('submit', function(e) {
  e.preventDefault();
  let inputStr = document.getElementById('string-to-slug').value
  slugifyString(inputStr);
  document.getElementById('slugged-string').innerHTML = newStr;
});
#slugged-string {
  color: green;
  font-size: 15px;
  padding-top: 20px;
}
<form id="slug-a-string-form" action="POST">
  <input type="text" id="string-to-slug" placeholder="enter the string to want to slug here...">
  <input type="submit" value="Submit">
</form>

<div id="slugged-string"></div>

这适用于像这样的字符串:

Testing This Out With Something TitleLike

虽然它很笨拙,但它是说禁止使用的字符存在时不存在。为什么会这样?

How to check if a string contains text from an array of substrings in JavaScript?

我稍微调整了一下并尝试了这个:

let newStr;

function slugifyString(str) {
  let forbiddenChars = ["&", "'", ","];
    newStr = str.toLowerCase().replace(/\s/g, '-');
  let forbiddenCharsLength = forbiddenChars.length;
    while(forbiddenCharsLength--) {
    if (newStr.indexOf(forbiddenChars[forbiddenCharsLength])!=-1) {
      if(forbiddenChars[forbiddenCharsLength] == "&") {
        newStr = newStr.replace("-&", '')
      } else {
        newStr = newStr.replace(forbiddenChars[forbiddenCharsLength], '')
      }
    }
  }
}

document.getElementById('slug-a-string-form').addEventListener('submit', function(e) {
  e.preventDefault();
  let inputStr = document.getElementById('string-to-slug').value
  slugifyString(inputStr);
  document.getElementById('slugged-string').innerHTML = newStr;
});
#slugged-string {
  color: green;
  font-size: 15px;
  padding-top: 20px;
}
<form id="slug-a-string-form" action="POST">
  <input type="text" id="string-to-slug" placeholder="enter the string to want to slug here...">
  <input type="submit" value="Submit">
</form>

<div id="slugged-string"></div>

基于控制台的输出:

it is: '
it is: &

它似乎在对禁用字符的每次迭代进行循环。

正在输入:

Ok Now Let's Do This & See

我们现在得到正确的输出:

ok-now-lets-do-this-see

但是我们说:

Ok Now Let's Do This & That & See, what happens if we have more than one, comma

我们得到:

ok-now-lets-do-this-that-&-see-what-happens-if-we-have-more-than-one,-comma

我不确定为什么它不删除所有被禁止的字符,因为我们正在遍历它。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

If pattern is a string, only the first occurrence will be replaced.

我知道它只会替换一次,但是

while(forbiddenCharsLength--) {
    if (newStr.indexOf(forbiddenChars[forbiddenCharsLength])!=-1) {
      if(forbiddenChars[forbiddenCharsLength] == "&") {
        newStr = newStr.replace("-&", '')
      } else {
        newStr = newStr.replace(forbiddenChars[forbiddenCharsLength], '')
      }
    }

我们正在做一个 while 循环并在每个匹配项上执行一个 if 命令,所以不应该为每个实例替换 运行..?

我在这里错过了什么?

尝试使用 replaceAll 函数而不是 replace。

您可以将每个字母的字符串拆分为一个数组,然后删除(映射到“”)每个禁止使用的字母并继续将空格替换为 -

  let forbiddenChars = ["&", "'", ","];
  let newStr = str
    .toLowerCase()
    .split("")
    .map(ch => forbiddenChars.includes(ch) ? '' : ch)
    .join("")
    .replace(/\s/g, '-');

function slugifyString(str) {
  let forbiddenChars = ["&", "'", ","];
  let newStr = str
    .toLowerCase()
    .split("")
    .map(ch => forbiddenChars.includes(ch) ? '' : ch)
    .join("")
    .replace(/\s/g, '-');
  if (newStr.includes(forbiddenChars) > -1) {
    console.log('a forbidden character is present')
  }
  return newStr;
}

document.getElementById('slug-a-string-form').addEventListener('submit', function(e) {
  e.preventDefault();
  let inputStr = document.getElementById('string-to-slug').value
  let outputStr = slugifyString(inputStr);
  document.getElementById('slugged-string').innerHTML = outputStr;
});
#slugged-string {
  color: green;
  font-size: 15px;
  padding-top: 20px;
}
<form id="slug-a-string-form" action="POST">
  <input type="text" id="string-to-slug" placeholder="enter the string to want to slug here...">
  <input type="submit" value="Submit">
</form>

<div id="slugged-string"></div>

您可能想试试这个解决方案:

const s = "Ok Now Let's Do This & That & See, what happens if we have more than one, comma";

const slug = s.replaceAll(/[',&]/g, '').replaceAll(/\s+/g, '-').toLowerCase();

console.log(slug);

您可以用不需要的 characters/substrings 迭代数组,并将最后的空格替换为破折号。

function slugify(s) {
    return ['&', ',', '\'']
        .reduce((s, c) => s.replaceAll(c, ' '), s)
        .replace(/\s+/g, '-');
}

console.log(slugify('Ok Now Let\'s Do This & That & See, what happens if we have more than one, comma'));