Abstract
In the web applications we develop, processing strings is the most commonly used function, this post will introduce : ① How to replace Javascript strings? ② How to split a string to generate an array? ③ How to slice a string by index?
Keywords: Javascript , strings , replace , split , slice.
Replace
In Javascript, replacing the content of a string requires the use of the replace() function. Here are a few common examples.
var test_str="here is an example
\n";
//1.repplace normal string
var replace_1=test_str.replace('example','test');
// result "
here is an test
\n"
//replace \n or \r
var replace_2=test_str.replace(/[\n\r]/ig, "[test]");
// result "
here is an example
[test]"
//3.clear <> and content
var replace_3=test_str.replace(/<.*?>/ig, "");
// result "here is an example\n"
Split
In Javascript, splitting a string needs to use the split() function, and specify what character to split according to, the function returns an array.
var test_str="here is an example \n for split";
var result_array=test_str.split('\n');
// result_array=['here is an example','','for split']
// the same string of split string will become '' and in result array
Slice
In Javascript, you need to use slice(start, end) function to intercept a string, where start represents the start-offset and end represents the end-offset.
var test_str="here is an example for slice";
var result_str=test_str.slice(0,3);
// result_str='here'
Summarize
In Javascript, we can use replace(), split(), slice() functions to replace, split, and intercept strings respectively. The result type returned by split() is array. For other operations of array type, please read related articles.
Related articles
Coming soon
If yuo have any question or need any help
you can leave a comment or connect me with weichaoxu1998@gmail.com