简体   繁体   English

从带有空格的字符串中删除单词

[英]remove word from string with spaces

  • I want to remove word from string including white spaces.我想从字符串包括空格删除Word。
  • For example if the string is 'dog cat cow' and you remove 'dog' it will return 'cat cow' .例如,如果字符串是'dog cat cow'并且您删除'dog'它将返回'cat cow'
  • If you want to remove 'cat' it would return 'dog cow' .如果你想删除'cat'它会返回'dog cow' It need to be removed white spaces before or/and after word also.它也需要在单词之前或/和之后删除空格。

To remove a particular word from a string along with whitespaces you can use this following function要从字符串中删除特定单词以及空格,您可以使用以下函数

function removeWord(sentence, word){
    sentence=sentence.split(" ").filter((item)=>{return item!=word}).join().replace(","," ");
    return sentence;
}

Could be done like this:可以这样做:

var str = "dog cat cow";
var word = 'cat';

console.log(replace(str, word));

function replace(str, word){
  str = str.replace(word, ""); // removing chosen word
  str = str.replace(/\s/g,''); //  removing whitespace
  return str;

}

Not the smallest solution but simplest imo.不是最小的解决方案,而是最简单的imo。

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

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