Home  >  Article  >  Web Front-end  >  How to reverse sentences in javascript

How to reverse sentences in javascript

青灯夜游
青灯夜游Original
2021-10-18 15:24:582022browse

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.

How to reverse sentences in javascript

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(&#39;&#39;).reverse().join(&#39;&#39;);
	}
</script>

Rendering:

How to reverse sentences in javascript

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn