How to use replace, split and slice methods of strings in Javascript?


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.


In Javascript, replacing the content of a string requires the use of the replace() function. Here are a few common examples.

					var test_str="<p title='example'>here is an example<p>\n";

//1.repplace normal string
var replace_1=test_str.replace('example','test'); 
// result "<p title='test'>here is an test<p>\n"

//replace \n or \r
var replace_2=test_str.replace(/[\n\r]/ig, "[test]");
// result "<p title='example'>here is an example<p>[test]"

//3.clear <> and content
var replace_3=test_str.replace(/<.*?>/ig, "");

// result "here is an example\n"



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



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'



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

Edit Template

Leave a Reply

Your email address will not be published. Required fields are marked *

Chaoxu Wei

Master student at Tongji University (Writer & Blogger)

Job hunting, both part-time and full-time jobs are accepted. Job recommendation please email me, thank you very much!


Edit Template

“There are many people in the world who want to work hard but can’t, and people who work too hard and are exhausted. Please don’t use your efforts only to chase your own victory, please use them to help others.”




Yangpu District, Shanghai