nlr_p nlr_p - 1 year ago 185
Node.js Question

How to replace string in Javascript

I am trying to replace

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);

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

mmm mmm
Answer Source

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, '');


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download