Create a program to swap the adjacent character using the javascript. In this example, let’s create a simple web page to design and perform swap functions using JS.
Swap the adjacent character of string using replace()
Problem Statement
In this, we have to swap the adjacent character in a string using the javascript function. For that create an HTML file and use the JS function that displays the result.
Solution
- Create an HTML file
- Add first heading in <h2></h2> tag is Swapping a adjacent character in string
- Add string using <b></b> tag The swapping string is :-AAAABBBBCCC FFF
- In javascript declare string using var and use replace() method to replace character of string var result = “AAAABBBBCCC FFF”.replace( /CCC/g, “DDD”);
- Display output string using document.write(“After swapping string is :”+(result));
JS code to swap the adjacent character using javascript
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> Swapping characters</title> </head> <body> <div style=" width: 300px; border: 15px solid green; padding: 50px; margin: 50px;"> <h2 style="color: red;">Swapping of adjacent character in string </h2> <b style="color:gray;">The swapping string is :-AAAABBBBCCC FFF</b><br/><br/> <script type="text/javascript"> var result = "AAAABBBBCCC FFF".replace( /CCC/g, "DDD"); document.write("After swapping string is :"+(result)); </script> </div> </body> </html>
Output
Swap adjacent character of string using split() and join()
Problem statement
In this task, create a program to swap the adjacent character of string using split() and join() in javascript. for that create an HTML file and use JS functions that display output.
Solution
- Create HTML file
- Enter heading in bold tag as <b>Swap string using split() and join()</b>
- Enter string var str = “virat kohli”; print that string using document.write (“</br>”+”Original string is-“+ str) ;
- Initialize var myArr = string.split() method to split string and output array var outptArr = [];
- For swapping the string use for loop for (i=0; i<myArr.length; i=i+2)
- Use arr.push() method to push one or more values into array outptArr.push(myArr[i+1]);
- Print output and use join() method to combine array ,using document.write(“</br>”+”After swapping string is- “+outptArr.join(”));
JS code to swap adjacent character using split() & join()
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> </title> </head> <body> <b>Swap string using split() and join()</b> <script> var str = "virat kohli"; document.write ("</br>"+"Original string is-"+ str); var myArr = str.split(''); var outptArr = []; for (i=0; i<myArr.length; i=i+2) { outptArr.push(myArr[i+1]); outptArr.push(myArr[i]); } document.write("</br>"+"After swapping string is- "+outptArr.join('')); </script> </body> </html>
Output
In this way, we learn how to swap adjacent characters using javascript.