How can I cut a string after X characters in JavaScript?

To cut a string after X characters, use substr() function from JavaScript. Following is the JavaScript code wherein we are cutting the string after 9th character −


var myName="JohnSmithMITUS";
console.log("The String="+myName)
var afterXCharacter = myName.substr(0, 9) + "\u0026";
console.log("After cutting the characters the string="+afterXCharacter);

Above, the unicode “\u0026” will replace all the characters with &(“\u0026”).

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo34.js.


This will produce the following output.

PS C:\Users\Amit\JavaScript-code> node demo34.js
The String=JohnSmithMITUS
After cutting the characters the string=JohnSmith&

Updated on: 01-Sep-2020


Kickstart Your Career

Get certified by completing the course

Get Started