nlr_p nlr_p - 3 months ago 23
Node.js Question

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.

mmm mmm
Answer

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>
Comments