繁体   English   中英

使用方法 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

删除& , ' , and ,字符

 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

它很笨拙,但它表示存在被禁止的字符,但实际上它不存在。 为什么会这样?

如何检查字符串是否包含 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

如果 pattern 是字符串,则只会替换第一个出现的位置。

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

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

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

我在这里缺少什么?

尝试使用 replaceAll 函数而不是替换。

您可能想尝试以下解决方案:

 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);

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

  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>

您可以使用不需要的字符/子字符串迭代数组,并用破折号替换最后的空格。

 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'));

暂无
暂无

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

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