Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

javascript - jQuery查找并替换字符串(jQuery find and replace string)

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows".(我在网站上的某个地方有一个特定的文本,例如“ lollypops”,我想用“ marshmellows”替换所有出现的字符串。)

The problem is that I don't know where exactly the text is.(问题是我不知道确切的文本在哪里。) I know I could do something like:(我知道我可以做类似的事情:) $(body).html($(body).html().replace('lollypops', 'marshmellows')); This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:(这可能会起作用,但是我需要尽可能少地重写HTML,因此我在考虑以下内容:) search for the string(搜索字符串) find the closest parent element(找到最接近的父元素) rewrite only the closest parent element(仅重写最接近的父元素) replace this even in attributes, but not all, for example replace it in class , but not in src(甚至在属性中替换它,但不是全部替换,例如,在class替换它,但不在src) In example, I would have structure like this(例如,我将具有这样的结构) <body> <div> <div> <p> <h1> <a>lollypops</a> </h1> </p> <span>lollypops</span> </div> </div> <p> <span class="lollypops">Hello, World!</span> <img src="/lollypops.jpg" alt="Cool image" /> </p> <body> In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span> s.(在此示例中,每次出现的“棒棒糖”都将被替换,只有<img src="...保持不变,并且唯一会被实际操纵的元素是<a>和两个<span> 。)
Does anybody know how to do this?(有人知道怎么做这个吗?)   ask by cypher translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could do something like this:(您可以执行以下操作:)

$("span, p").each(function() { var text = $(this).text(); text = text.replace("lollypops", "marshmellows"); $(this).text(text); }); It will be better to mark all tags with text that needs to be examined with a suitable class name.(最好用需要使用适当的类名检查的文本标记所有标签。) Also, this may have performance issues.(另外,这可能会出现性能问题。) jQuery or javascript in general aren't really suitable for this kind of operations.(一般而言,jQuery或javascript并不真正适合此类操作。) You are better off doing it server side.(您最好在服务器端执行此操作。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...