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

JavascriptWeb DevelopmentObject Oriented Programming

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 −

Example

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.

Output

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&
raja
Published on 01-Sep-2020 11:26:24
Advertisements