查找和替换文本的Javascript [英] Javascript to find and replace text

查看:127
本文介绍了查找和替换文本的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为google chrome进行扩展,我希望能够找到某些文本,并使用javascript用随机字母或数字替换它们,但某些文本是用户输入的变量,例如,他们输入了如前所述,找到并替换了狗"一词和所有说狗"的词.帮助非常需要

I'm making an extension for google chrome and i would like to be able find certain pieces of text and replace them with random letters or numbers using javascript except the certain text is a variable entered by the user for example they enter the word dog and all words that say dog are found and replaced as explained before . HELP greatly wanted

推荐答案

尝试使用JavaScript的.replace()方法. 假设您有一个像这样的div,用于包含文本:<div id="test">Original Text</div>,请使用此JavaScript代码:

Try using the .replace() method of JavaScript. Supposing you have a div like so for containing text: <div id="test">Original Text</div>, use this JavaScript code:

var orignalstring = document.getElementById("test").innerHTML;
var newstring = orignalstring.replace("original","replaced");
document.getElementById("test").innerHTML = newstring;

基本上,这将标识整个div的全部内容,然后查找某些文本并替换这些术语,如您所问的那样.如果要在一个命令中替换多个字符串,请尝试以下操作:如何使用.replace()方法替换多个字符串?.这是我几周前问到的有关.replace()的问题.

Basically, this will identify the entire content of the whole div, then find certain text and replace those terms, like you asked. If you want to replace multiple strings in one command, try this: How to replace multiple strings with the .replace() Method?. This is a question I asked a few weeks back about .replace().

此外,请尝试以下JSFiddle: http://jsfiddle.net/tGMaN/

Also, try this JSFiddle: http://jsfiddle.net/tGMaN/

如果希望用户能够定义要替换的文本和替换文本,则可以通过文本字段或提示框轻松地执行此操作,并且这些值可以存储为在方法.

If you want the user to be able to define the text to replace and the replacement text, you can easily do this through text fields or a prompt box, and these values can be stored as variables which are called in the .replace() method.

这篇关于查找和替换文本的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆