繁体   English   中英

用JavaScript替换段落中的文本

[英]Replace text in paragraph with JavaScript

对于我的应用程序,我有来自API的信息,该信息是一堆文本,放在段落标记之间。 但是,有时文本会显示“ null”。 如何删除任何包含“ null”的文本,并使用Javascript将其替换为“ No info”? 类似于发誓的过滤器。 在此处输入图片说明

只是

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

在此处输入图片说明

这样一来,你可以像disannulling转的话会变成disanNo Infoing。 因此,您应该使用regex来匹配规范字:

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

 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> 

要替换文本,可以使用String.prototype.replace()函数。

您可以像这样使用它:

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

检查一下: http : //jsfiddle.net/a9osg2zp/

您可以使用替换功能。

如果要替换倍数,则需要使用正则表达式。

例如,

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

输出: "goodbye hello"

"hello hello".replace(/hello/g,"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