Home  >  Article  >  Web Front-end  >  JavaScript string insertion, deletion, and replacement function usage examples_javascript skills

JavaScript string insertion, deletion, and replacement function usage examples_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:28:051219browse
Explanation:

The first two functions in the following functions take out the first part and the last part of the search string for use in other functions. Note that calling the replaceString(mainStr,searchStr,replaceStr) function once can only replace the first searchStr string found in the string mainStr with the replaceStr string, but cannot replace all the searchStr strings in the string mainStr with replaceStr. String, if you need to replace all, you need to use a loop.

Function source code:
[code
//Extract all characters in front of the search string
function getFront(mainStr,searchStr){
foundOffset=mainStr .indexOf(searchStr);
if(foundOffset==-1){
return null;
}
return mainStr.substring(0,foundOffset);
}
[/ code]
Copy code The code is as follows:

//Extract all characters after the search string
function getEnd(mainStr,searchStr){
foundOffset=mainStr.indexOf(searchStr);
if(foundOffset==-1){
return null;
}
return mainStr .substring(foundOffset searchStr.length,mainStr.length);
}

Copy code Code As follows:

//Insert the string insertStr in front of the string searchStr
function insertString(mainStr,searchStr,insertStr){
var front=getFront(mainStr,searchStr);
var end=getEnd(mainStr,searchStr);
if(front!=null && end!=null){
return front insertStr searchStr end;
}
return null;
}

Copy code The code is as follows:

//Delete the string deleteStr
function deleteString(mainStr,deleteStr){
return replaceString(mainStr,deleteStr,"");
}

Copy the code The code is as follows:

//Change the string searchStr to replaceStr
function replaceString(mainStr,searchStr,replaceStr){
var front =getFront(mainStr,searchStr);
var end=getEnd(mainStr,searchStr);
if(front!=null && end!=null){
return front replaceStr end;
}
return null;
}

Usage example:
Suppose there is a form used to receive user messages. We need to replace the carriage return and line feed entered by the user in the message content with the HTML tag
, and also replace the space character with , so that when the message information is displayed, it can be displayed in the original format entered by the user.
The html file is as follows:
Copy the code The code is as follows: