简体   繁体   中英

Add “-” for every word - javascript

For every word that is entered into the text box I want to add a "-" before each word except for words like "is" and "was".

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

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

}

What am I missing here?

Try this: 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>

Or if you have some special words, you can use this 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);
        });             
    });

Why you don't use replace method?

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

I know it's already answered, but I figured why not. Some one might like this other method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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