MMR
MMR

Reputation: 3009

How to replace string in Javascript

I am trying to replace '<p>hi</p>' with 'hi'

My JavaScript:

var obj = {item:{title: params.title,description: params.text, link: req.headers['origin']+"/blog/blog-description/"+params.blog_id, guid:req.headers['origin']+"/blog/blog-description/"+params.blog_id}};

var xml2js = require('xml2js');     
var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);
var modXml = xml.replace('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', '');
var modXml = xml.replace(/<(?:.|\n)*?>/gm, '');         
var new_text = modXml;

fs.readFile('public/feed.xml', function read(err, data) {
    if (err) throw err;
    var file_content = data.toString();
    var c = file_content.indexOf('</description>');
    var position = c + 14;
    file_content = file_content.substring(position);
    var file = fs.openSync('public/feed.xml','r+');
    var bufferedText = new Buffer(new_text+file_content);
    fs.writeSync(file, bufferedText, 0, bufferedText.length, position);
    fs.close(file);
});

i didnt know where it went wrong can someone suggest help.

Upvotes: 0

Views: 1537

Answers (4)

Manchikanti Aishwarya
Manchikanti Aishwarya

Reputation: 290

Try this:

xml.split('<p>hi</p>').join('hi');

Upvotes: 2

baao
baao

Reputation: 73211

xml2js replaces your <p> tag with &lt;p&gt; (and the </p> with &lt;/p&gt;), so you need to replace the replaced string. Also, call Builder() with the headless: true option - then you don't need to replace the header. The following works:

var obj = {item:{title: '<p>foobarbaz</p>',description: "<p>foo</p>", link: "<p>bar</p>", guid:"<p>baz</p>"}};

var xml2js = require('xml2js');
var builder = new xml2js.Builder({ headless: true });
var xml = builder.buildObject(obj);
var modXml = xml.replace(/&lt;p&gt;|&lt;\/p&gt;/gm, '');
console.log(modXml);

Output:

<item>
  <title>fobaba</title>
  <description>foo</description>
  <link>bar</link>
  <guid>baz</guid>
</item>

Upvotes: 1

MoLow
MoLow

Reputation: 3084

you could either use a regex to strip tags, or use a library such as striptags

optional regex:

var text = '<p>aaa</p>';
console.log(text.replace(/<(?:.|\n)*?>/gm, ''));

striptags library could be used to strip all tags, or only specific tags:

var text = '<p>aaa</p>';
striptags(html);
striptags(html, ['p']);

Upvotes: 1

Chris
Chris

Reputation: 2364

Since replace is returning a string object, you can simply chain the calls:

Have you tried:

var modXml = xml.replace('<p>', '').replace("</p>",'');

I think you could also condense it into one regular expression.

Upvotes: 1

Related Questions