In JavaScript, first create a method that can replace the intermediate content; then use the substr method to extract text that does not need to be replaced. The syntax format is "String object.substr (starting position, number of characters)"; finally Just replace the content that needs to be replaced.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
If you want to replace the strings such as ID number or mobile phone number in the middle of the string
function replacepos(text,start,stop,replacetext){ let mystr = text.substr(0,start-1)+replacetext+text.substr(stop+1); return mystr; }, replacepos('测试文字csdn', 2, 4, "**") // 测试**csdn
substr() method can extract the specified number starting from the start subscript in the string character.
Syntax
stringObject.substr(start,length)
Return value
A new string containing start from stringObject (including the point pointed to by start characters) starting at length characters. If length is not specified, the returned string contains characters from start to the end of stringObject.
Tips and Notes
Note: The parameters of substr() specify the starting position and length of the substring, so it can be used instead of substring() and slice().
[Recommended learning:javascript advanced tutorial]
The above is the detailed content of How to replace intermediate content in JavaScript. For more information, please follow other related articles on the PHP Chinese website!