Home >Web Front-end >JS Tutorial >How to reverse sentences in javascript
Method: 1. Use the "Element.innerText" statement to obtain the text that needs to be reversed; 2. Use the "Text.split('').reverse().join('')" statement to get the text Reverse; 2. Use the "element.innerText=reverse text" statement to write the reversed text into the label element for display.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript implements sentence reversal
Implementation ideas:
First, obtain the sentence content .
Because you only need text content, you can use the innerText attribute; it will get all the text in the label (and its sub-labels), but not the label (or you can filter out all labels). If there are multiple spaces or newlines, it will be parsed as one space.
Then to reverse the obtained text content, you can use the str.split('').reverse().join('')
statement.
Finally, use the innerText attribute to rewrite the reversed text content into the label element and display it.
Implementation code:
<div id="demo1">欢迎来到PHP中文网!</div><br> <input type="button" value="点击按钮反转文字" id="btn"/><br><br> <div id="demo2"></div> <script type="text/javascript"> document.getElementById("btn").onclick=function(){ var div1=document.getElementById("demo1"); var div2=document.getElementById("demo2"); var text=div1.innerText; div2.innerText=text.split('').reverse().join(''); } </script>
Rendering:
[Recommended learning: JavaScript advanced tutorial】
The above is the detailed content of How to reverse sentences in javascript. For more information, please follow other related articles on the PHP Chinese website!