简体   繁体   English

使用Javascript替换文本框中的文本(更改大小写)

[英]Replace text (change case) in a textbox using Javascript

I am trying to build a sort of intelli-sense text input box, where as the user types, the 'and' is replaced by 'AND \\n' (ie on each 'and', the 'and' is capitalized and user goes to new line). 我正在尝试构建一种智能文本输入框,在用户输入的情况下,'和'被'AND \\ n'替换(即每个'和','和''大写,用户去到新线)。

The Javascript I used for this is: 我用于此的Javascript是:


function Validate()
{
document.getElementById("search").value =  document.getElementById("search").value.replace("and","AND \n"); //new line for AND
}

The HTML part is like this: HTML部分是这样的:

< textarea type="text" name="q" id="search" spellcheck="false" onkeyup='Validate();'>< /textarea>

Though the above script works well on Firefox and Chrome, it sort-of misbehaves on Internet Explorer (brings the cursor to the end of the text on each 'KeyUp'). 虽然上面的脚本在Firefox和Chrome上运行良好,但它在Internet Explorer上出现了一些错误的行为(将光标移到每个'KeyUp'上的文本末尾)。

Also the above code doesn't work for the other variants of 'and' like 'And', 'anD' or even 'AND' itself. 此外,上述代码不适用于'和'的其他变体,如'And','anD'或甚至'AND'本身。

I think the actual answer here is a mix of the two previous: 我认为这里的实际答案是前两者的混合:

onkeyup="this.value = this.value.replace(/\band\b/ig, ' AND\n')"

You need the i to make the search case insensitive and the g to make sure you replace all occurrences. 您需要i使搜索大小写不敏感,并且g需要确保替换所有出现的内容。 This is not very efficient, as it'll replace previous matches with itself, but it'll work. 这不是很有效,因为它将取代之前的匹配,但它会起作用。

To make it a separate function: 要使它成为一个单独的功能:

function validate() {
    document.getElementById('search') = document.getElementById('search').replace(/\band\b/ig, ' AND\n');
}

If you alter the textarea contents while the user is typing the caret will always move to the end, even in Firefox and Chrome. 如果您在用户输入时更改textarea内容,则插入符号将始终移至最后,即使在Firefox和Chrome中也是如此。 Just try to edit something you already wrote and you'll understand me. 只是尝试编辑你已经写过的东西,你就会理解我。 You have to move the caret to the exact position where the users expects it, which also implies you have to detect text selections (it's a standard behaviour that typing when you have a selection removes the selected text). 您必须将插入符移动到用户期望的确切位置,这也意味着您必须检测文本选择(当您有选择时,键入的标准行为将删除所选文本)。

You can find here some sample code . 你可以在这里找到一些示例代码 You might be able to use the doGetCaretPosition(), setCaretPosition() functions. 您可以使用doGetCaretPosition(),setCaretPosition()函数。

I tried to work around the problem and solved by using the following javascript: 我试图解决这个问题,并使用以下javascript解决:

function Validate() {
    if( document.getElementById("search").value.search(/\band$(?!\n)/i) >= 0 ){ // for maintaining cursor position
        document.getElementById("search").value =  document.getElementById("search").value.replace(/\band$(?!\n)/i,"AND\n"); //new line for AND
    }
}

Thin slicing the above problem and solution: 薄切片上述问题和解决方案:

1) The function was being called on each key up, thus earlier "AND\\n" was being repeated on each key up, thus inserting a blank line on each key press. 1)在每个按键上调用该功能,因此在每个按键上重复“AND \\ n”,因此在每个按键上插入一个空行。 I avoided the above by using the regex: 我通过使用正则表达式避免了上述情况:

/\band$(?!\n)/i
\\b = Like Word (to avoid S AND ) \\b =喜欢Word(避免S AND
$ = End of line (as "and" will be replaced by "AND\\n" thus it will always be end of line) $ =行尾(因为“和”将被“AND \\ n”取代,因此它将始终为行尾)
(?!\\n) = Not followed by new line (to prevent repeatedly replacing "AND\\n" on each key press) (?!\\n) =后面没有新行(为了防止在每次按键时反复更换“AND \\ n”)
i = To cover all variants of "and" including "And","anD" etc. i =涵盖“和”的所有变体,包括“和”,“和D”等。

2) Internet Explorer was misbehaving and the cursor position was not maintained (moved to end) when the input was re-edited. 2)重新编辑输入时,Internet Explorer行为不正常并且未保持光标位置(移动到结束)。 This was caused (as hinted by Alvaro above) due to the replace function. 这是由于替换功能引起的(正如上面的Alvaro所暗示的)。
Thus I inserted an "if" statement to call replace function only when it is needed, ie only when there is some "and" needing replacement. 因此,我只在需要时插入一个“if”语句来调用replace函数,即仅当有一些“和”需要替换时。

Thanks everyone for the help. 谢谢大家的帮助。

I think you want your replace call to look like this: 我想你希望你的replace调用看起来像这样:

replace(/\\band\\b/i,"AND \\n") (see below) replace(/\\band\\b/i,"AND \\n") (见下文)

That way it is not case sensitive ( /i ), and only takes single words that match and , so 'sand' and similar words that contain 'and' don't match, only 'and' on it's own. 这样,它不区分大小写( /i ),并且只需要匹配的单个单词and ,因此“沙”和包含类似的话“和”不匹配,只有“和”在它自己的。

EDIT : I played around with it based on the comments and I think this working example is what is wanted. 编辑 :我根据评论玩了它,我认为这个工作的例子是想要的。

Replace the onKeyUp event with onBlur : onBlur替换onKeyUp事件:

<textarea type="text" name="q" id="search" spellcheck="false" onblur='Validate();'></textarea></body>

So that the validate function is only run when the user leaves the text box. 因此, validate功能仅在用户离开文本框时运行。 You could also run it onSubmit . 你也可以在子onSubmit运行它。

I also added a global switch ( g ) and optional trailing whitespace ( \\s? ) to the regex: 我还在正则表达式中添加了一个全局开关( g )和可选的尾部空格( \\s? ):

replace(/\band\b\s?/ig,"AND \n")

This causes input like this: 这会导致这样的输入:

sand and clay and water

to be transformed into this when you leave the text box: 当你离开文本框时转换成这个:

sand AND
clay AND
water

You should probably test this against a bunch more cases. 您可能应该针对更多案例进行测试。

try using the following replace() statement: 尝试使用以下replace()语句:

replace(/\band(?!$)/ig, "And\n")

since this is being called repeatedly against the altered string you have to make sure that the "and" is not followed by a line break. 因为这是针对改变的字符串重复调用的,所以你必须确保“和”后面没有换行符。

example (uses a loop and function to simulate the user typing the letters in): 示例(使用循环和函数来模拟用户输入字母):

function onkeyup() {
     var str = this;
     return this.replace(/\band(?!$)/ig, "And\n");
};

var expected = "this is some sample text And\n is separated by more text And\n stuff";
var text = "this is some sample text and is separated by more text and stuff";
var input = "";
var output = "";

for(var i = 0, len = text.length; i < len; i++ ) {
    input += text.substr(i,1);
    output = onkeyup.call(input);
}

var result = expected == output;
alert(result);
if( !result ) {
   alert("expected: " + expected);
   alert("actual: " + output);
}

you can test this out here: http://bit.ly/8kWLtr 你可以在这里测试一下: http//bit.ly/8kWLtr

You need to write a JS code that run in both IE and FireFox. 您需要编写一个在IE和FireFox中运行的JS代码。 I think this is what you need: 我想这就是你需要的:

var s = document.getElementbyId('Search');
s.value = s.value.replace('and', 'AND \n');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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