繁体   English   中英

查找和替换不起作用

[英]Find & Replace not working

伙计们,当我尝试替换输入文本框中的某些值时,它仅替换第一个值,而不替换整个对话。

在“输入文本”框中,我的对话看起来像

用户1 Prefix_ago用户2 Prefix_ago用户1 Prefix_ago

我只想将prefix_ago替换为:

 function copy() { var text = document.getElementById('result1').value; document.getElementById('id1').innerHTML = text; $('#id1').each(function() { var text = $(this).text(); $(this).text(text.replace('prefix_ago', ' : ')); }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea class="result" id="result1" rows="10" cols="150" style="font-size:11px;resize: none; width:225px;"></textarea> <button class="btn58" id="btn" onClick="copy()"> Copy & Replace</button> <div id="id1"> </div> 

我有一个名为Prefix_ago值,该值在我的段落中重复多次,我想将其替换为冒号“:”,该代码可以正常工作,但仅替换第一个值而不是整个段落

答案的核心是,您需要在正则表达式中包含“ g”选项,以使其匹配多个实例。

就是说,您使代码过于复杂了-不需要$.each在单个输出字段上,也不需要在更改之前将文本复制到输出字段中。 这是一个简化的版本:

 function copy() { var txt = $('#result1').val().replace(/prefix_ago/g, ' : '); txt = txt.replace(/\\n/g, '<br>'); // <-- per comments below $('#id1').html(txt); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="result1" rows="10" cols="150"> test prefix_ago test prefix_ago test test prefix_ago test prefix_ago test </textarea> <button onclick="copy()"> Copy & Replace</button> <div id="id1"> </div> 

暂无
暂无

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

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