如何实时大写text_field单词,不包括介词



如何像这个网站一样对单词进行标题/捕获,以便不包括介词?

我不是想让你列出所有的介词,但如果你能展示如何用一些介词来完成,比如"的,在,和",我将不胜感激。

<%= f.text_area :name, id: "challenge-name" %>
<script> # This code capitalizes ALL words
  function makeTitle(slug) {
    var words = slug.split(' ');
    $.each(words, function(index, word){
        words[index] = word.charAt(0).toUpperCase() + word.slice(1);
    });
    return words.join(' ');
  }
  $('#challenge-name').on('keyup', function(){ $(this).val( makeTitle($(this).val())) })
</script>

根据弗雷德的回答进行更新

function makeTitle(slug) {
  var preps = ['and', 'a', 'of', 'but', 'from'];
  return $.map(slug.split(' '), function(k, v) {
    return $.inArray(k.match(/w*/g)[0], preps) >= 0 ? k : k[0].toUpperCase() + k.slice(1);
  }).join(' ');
}
$('#challenge-name').on('keyup', function(){ $(this).val( makeTitle($(this).val())) })

您可能需要注意标点符号 - 此代码考虑了标点符号:

def makeTitle(slug)
  preps = ['and', 'a']
  str.split(' ').map do |w| 
    preps.include?(/w*/.match(w)[0]) ? w : w.capitalize 
  end.join ' '
end

我会责怪上个晚上的深夜 - 我没有意识到OP想要一个jquery/javascript解决方案,所以我在Ruby中创建了一个。我将保留它,以防将来的观众在 Ruby 中寻找答案,但这里有一个 JS 方法(使用 jQuery):

function makeTitle(slug) {
  var preps = ['and', 'a'];
  return $.map(slug.split(' '), function(k, v) {
    if(k){
        var word = k.match(/w*/g)[0].toLowerCase();
      var letter = $.inArray(word, preps) >= 0 ? k[0].toLowerCase() : k[0].toUpperCase();
        return letter + k.slice(1);
    } else {
      return k;
    }
  }).join(' ');
}

你可以用不同的编码方法这样做;

var preps = ["of", "on", "and", "or", "in", "a", "the"],
      str = "the mother of the sea and a life in the depths of the ocean",
    words = str.match(/bw+b/g);
   header = words.map((e,i) => preps.indexOf(e) == -1 || i === 0 ? e[0].toUpperCase()+e.slice(1) : e).join(" ");
console.log(header);

当然,您可以包括您希望保持原样的介词,并在preps数组中排除不保留的内容。

根据您的代码; 我更愿意修改如下;

function makeTitle(slug) {
  var words = slug.match(/bw+b/g),
      preps = ["of", "on", "and", "or", "in", "a", "the"];
  return words.map((e,i) => preps.indexOf(e) == -1 || i === 0 ? e[0].toUpperCase()+e.slice(1) : e).join(" ");
}

这是ES5版本,应该可以与Safari和不支持JS箭头的Chrome,Firefox和IE的旧版本一起使用。

function makeTitle(slug) {
  var words = slug.match(/bw+b/g),
      preps = ["of", "on", "and", "or", "in", "a", "the"];
  return words.map(function(e,i) {
                     return preps.indexOf(e) == -1 || i === 0 ? e[0].toUpperCase()+e.slice(1) : e;
                   }).join(" ");
}
var s = makeTitle("the mother of the sea and a life in the depths of the ocean");
console.log(s);

最新更新