简体   繁体   English

JavaScript-用标签替换文本

[英]javascript - replace text with tags

i do not know much about javascript searched long, but didn't get the reslut i need. 我对javascript搜索时间了解不多,但没有得到我需要的结果。

i want to replace on page load this 我想替换页面加载此

<p>---SOMERANDOMTEXT:::</p>

with

<strong>SOMERANDOMTEXT</strong>

played with this an many other snippets.. 玩了很多其他片段。

<script type="text/javascript">
    window.onload = function() {
        function myscript() {
            input = '---';
            output='New Text';
            document.body.innerHTML = document.body.innerHTML.replace(input,output);
        }
    }
</script>

Here is the fast and fool proof way of replacing <p> tags with <strong> tags: 这是用<strong>标签替换<p>标签的快捷方法:

var ps = document.getElementsByTagName('p');
for (var i = ps.length; i--;) {
    var strong = document.createElement('strong'),
        p = ps[i];

    while (p.firstChild) {
        strong.appendChild(p.firstChild);
    }

    p.parentNode.insertBefore(strong, p);
    p.parentNode.removeChild(p);
}

If you need to change the text accordingly, place something like that in the while loop: 如果需要相应地更改文本,请将类似的内容放入while循环中:

if (p.firstChild.nodeType === 3) {
    p.firstChild.nodeValue = p.firstChild.nodeValue.replace(/[-:]{3}/g, '');
}

DEMO: http://jsfiddle.net/5m9Qm/1/ 演示: http : //jsfiddle.net/5m9Qm/1/

You need to call your myscript function like this - 您需要这样调用myscript函数-

window.onload = function() {
  myscript();
}
function myscript() {
    var input = '---';
    var output='New Text';
    document.body.innerHTML = document.body.innerHTML.replace(input,output);
}

You are declaring a function myscript but never invoking it. 您在声明函数myscript但从未调用它。 Try this (untested) code: 试试这个(未经测试的)代码:

<script>
window.onload = function(){
    var p = document.querySelector('p');
    var strong = document.createElement('strong');
    strong.innerHTML = 'replaced';
    p.parentNode.replaceChild(strong,p);

})
</script>

Note this requires modern browsers. 请注意,这需要现代浏览器。

You can use a regex. 您可以使用正则表达式。

Try: 尝试:

output = document.body.innerText.replace(/[-:]{3}/g, '');
document.body.innerHTML = document.body.innerHTML.replace(/<p>---.*:::<\/p>/, '<strong>' + output + '</strong>');

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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