简体   繁体   中英

replace number between two tags javascript

var input = " <root> <date>1995-03-03</date> <heure>13:33</heure> <day0>2</day0> <day1>0</day1> <day2>0</day2> <no2>1</no2> <pm10>2</pm10> <day0_o3>0</day0_o3> <day1_o3>0</day1_o3> <day2_o3>0</day2_o3> </root>"

Suppose i want to update day0 value as 6, then output will be

OutPut = " <root> <date>1995-03-03</date> <heure>13:33</heure> <day0>6</day0> <day1>0</day1> <day2>0</day2> <no2>1</no2> <pm10>2</pm10> <day0_o3>0</day0_o3> <day1_o3>0</day1_o3> <day2_o3>0</day2_o3> </root>"

Thanks for the response i have fixed this

input.replace(/<day0>.*<\/day0>/, '<day0>6</day0>');

im not sure how you get the input but if its from the DOM, you can use document.getElementsByTagName("day0")[0].innerText = "new output";

please give a bit more details if you meant something else

Using pure javascript you can write something like this:

document.querySelector("day0").textContent = "6";

If you should support browsers, that do now know about textContent, you can write:

document.querySelector("day0").innerText = "6";

Do not use innerHTML to replace text to prevent XSS vulnerability.

You could also write your own little function to look for the tags in the string, assuming the input will always be a string with tags in it.

for example:

var replaceValueInTag = (tags, tagName, newValue) => {
    var startTag = `<${tagName}>`;
    var endTag = `</${tagName}>`;

    var indexOfStartTag = tags.indexOf(startTag);
    var indexOfEndTag = tags.indexOf(endTag);

    var value = tags.substring(indexOfStartTag + startTag.length, indexOfEndTag);

    return tags.replace(`${startTag}${value}${endTag}`, `${startTag}${newValue}${endTag}`); 
}

var tags = " <root> <date>1995-03-03</date> <heure>13:33</heure> <day0>2</day0> <day1>0</day1> <day2>0</day2> <no2>1</no2> <pm10>2</pm10> <day0_o3>0</day0_o3> <day1_o3>0</day1_o3> <day2_o3>0</day2_o3> </root>":

replaceValueInTag(tags, 'day0', '6');

// output: 
// <root> <date>1995-03-03</date> <heure>13:33</heure> <day0>6</day0> <day1>0</day1> <day2>0</day2> <no2>1</no2> <pm10>2</pm10> <day0_o3>0</day0_o3> <day1_o3>0</day1_o3> <day2_o3>0</day2_o3> </root>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM