[英]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". 我想为输入到文本框中的每个单词在每个单词之前添加一个“-”,除了“ is”和“ 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: 试试这个: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: HTML:
<textarea id='WhatTextBox'></textarea>
<div id='newtext'></div>
Or if you have some special words, you can use this javascript: 或者,如果您有一些特殊的单词,则可以使用以下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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.