Josh O'Connor
Josh O'Connor

Reputation: 4962

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. 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.enter image description here

Upvotes: 0

Views: 208

Answers (4)

iplus26
iplus26

Reputation: 2637

Just

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

enter image description here

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>    

Upvotes: 2

Oliver
Oliver

Reputation: 1644

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

Upvotes: 0

Chris
Chris

Reputation: 2806

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"

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

Outputs: "goodbye goodbye"

Upvotes: 0

Johan Karlsson
Johan Karlsson

Reputation: 6476

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/

Upvotes: 0

Related Questions