簡體   English   中英

為每個單詞添加“-”-javascript

[英]Add “-” for every word - javascript

我想為輸入到文本框中的每個單詞在每個單詞之前添加一個“-”,除了“ is”和“ was”之類的單詞。

$('#WhatTextBox').keyup(function() {
        var word_check = $('#WhatTextBox').val();
        if(!word_check.match('is') OR !word_check.match(' ')) {

            $('#special'("-"+$('#WhatTextBox').val());

}

我在這里想念什么?

試試這個:Javascript:

    $(document).ready(function (){
        $('#WhatTextBox').keyup(function() {
            var text = $(this).val();
            text = text.split(" ");
            var newtext = "";
            for(var i=0;i<text.length;i++){
                if (text[i] == 'is' || text[i] == 'was'){
                    newtext = newtext+" "+text[i];
                }else{
                    newtext = newtext+"-"+text[i];
                }
            }
            $("#newtext").text(newtext);
        });             
    });

HTML:

<textarea id='WhatTextBox'></textarea>
<div id='newtext'></div>

或者,如果您有一些特殊的單詞,則可以使用以下javascript:

    $(document).ready(function (){
        var specialwords = ['is','was','am','are'];//special words here
        $('#WhatTextBox').keyup(function() {
            var text = $(this).val();
            text = text.split(" ");
            var newtext = "";
            for(var i=0;i<text.length;i++){
                if (specialwords.indexOf(text[i])!=-1){
                    newtext = newtext+" "+text[i];
                }else{
                    newtext = newtext+"-"+text[i];
                }
            }
            $("#newtext").text(newtext);
        });             
    });

為什么不使用替換方法?

$('#WhatTextBox').keyup(function() {
        $('#WhatTextBox').val($('#WhatTextBox').val().replace(' ', '-').replace('-is', ' Is').replace('-was', ' was'));
}

我知道已經回答了,但我想為什么不呢。 有人可能會喜歡另一種方法。

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<textarea id="WhatTextBox">
</textarea>
<script>

$('#WhatTextBox').keyup(function() {
    var val = ' '+this.value;
    var exempt = ['is', 'was'];
    var value = val.replace(/(\s)([\S]+)/g, function(m, space, word){

        var tmp = word.slice(1, word.length);
        if(exempt.indexOf(tmp) !== -1){
            return space+tmp;
        }else if(exempt.indexOf(word) !== -1 || word[0] === '-'){
            return space+word;
        }

        return space+'-'+word;
    });

    this.value = value.slice(1, value.length);
});
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM