For my app I have information from an API coming in, which is a bunch of text, put in between paragraph tags. However, sometimes the text will say "null". How do I remove any text which has "null" and replace it with "No info" with Javascript? Similar to a swear filter.
4 Answers
Just
all_string.replace('null', 'No Info');
In that way, you may trans words like disannulling will be turned into disanNo Infoing. So you should use regex to match the spec null word:
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>
5 Comments
Josh O'Connor
What if I dont know the string name but I want to check all text in the body?
iplus26
@JoshO'Connor You don't have to know the string name.
all_string is just the name of the variable set by you. In this case, if you're using AJAX to get the string from some APIs, set the responseText to all_string. Sorry for my poor English, did I make myself clear?Josh O'Connor
It doesnt work... I am trying to replace everything in the <p > tags, not a variable..
Josh O'Connor
Ok sounds good. Im elbows deep in another project, I will definitely get back to it in a few days, and then I will upvote if correct... plz bear with me and be patient :)
To replace text you can use the String.prototype.replace() function.
You can use it like this:
YOUR_STRING = YOUR_STRING.replace(/\bnull\b/g, "No info");
Check it out: http://jsfiddle.net/a9osg2zp/
