如何在实时排除介词的情况下将text_field单词大写?

时间:2016-06-05 22:13:04

标签: javascript jquery ruby-on-rails ruby

如何标记/封闭字词,例如website,以便不包含介词?

我没有找你列出所有的介词,但是如果你能说明如何用#34; of,on和"我将不胜感激。

<%= 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>

基于FRED的答案的更新

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())) })

2 个答案:

答案 0 :(得分:1)

您可能需要注意标点符号 - 此代码会将标点符号考虑在内:

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

答案 1 :(得分:0)

你可以用不同的编码方法来做这件事;

&#13;
&#13;
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(/\b\w+\b/g);
   header = words.map((e,i) => preps.indexOf(e) == -1 || i === 0 ? e[0].toUpperCase()+e.slice(1) : e).join(" ");
console.log(header);
&#13;
&#13;
&#13;

当然,您可以包含您希望保留的介词,并将其排除在preps数组之外。

根据您的代码;我宁愿按如下方式修改它;

function makeTitle(slug) {
  var words = slug.match(/\b\w+\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和较旧版本的Chrome,Firefox和IE,它们不支持JS箭头。

&#13;
&#13;
function makeTitle(slug) {
  var words = slug.match(/\b\w+\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);
&#13;
&#13;
&#13;