简体   繁体   English

用JavaScript替换段落中的文本

[英]Replace text in paragraph with JavaScript

For my app I have information from an API coming in, which is a bunch of text, put in between paragraph tags. 对于我的应用程序,我有来自API的信息,该信息是一堆文本,放在段落标记之间。 However, sometimes the text will say "null". 但是,有时文本会显示“ null”。 How do I remove any text which has "null" and replace it with "No info" with Javascript? 如何删除任何包含“ null”的文本,并使用Javascript将其替换为“ No info”? Similar to a swear filter. 类似于发誓的过滤器。 在此处输入图片说明

Just 只是

all_string.replace('null', 'No Info');

在此处输入图片说明

In that way, you may trans words like disannulling will be turned into disanNo Infoing . 这样一来,你可以像disannulling转的话会变成disanNo Infoing。 So you should use regex to match the spec null word: 因此,您应该使用regex来匹配规范字:

all_string.replace(/\bnull\b/g, 'No Info');

Example

 var element = document.querySelector('p'); element.innerHTML = element.innerHTML.replace(/\\bnull\\b/g, 'No Info'); 
 <p>this is the first null line. another null null null. thisnull will not be replaced. </p> 

To replace text you can use the String.prototype.replace() function. 要替换文本,可以使用String.prototype.replace()函数。

You can use it like this: 您可以像这样使用它:

YOUR_STRING = YOUR_STRING.replace(/\bnull\b/g, "No info");

Check it out: http://jsfiddle.net/a9osg2zp/ 检查一下: http : //jsfiddle.net/a9osg2zp/

You can use the replace function. 您可以使用替换功能。

If you want to replace multiples you will want to use regex. 如果要替换倍数,则需要使用正则表达式。

For example, 例如,

"hello hello".replace("hello","goodbye")

Outputs: "goodbye hello" 输出: "goodbye hello"

"hello hello".replace(/hello/g,"goodbye")

Outputs: "goodbye goodbye" 输出: "goodbye goodbye"

 while(APIString.indexOf('null') != -1){ APIString.replace('null','No info'); } 

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

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