Kalpesh Boghara Kalpesh Boghara - 2 years ago 96
Javascript Question

How to remove string between two words in javascript

How to remove string between two words in javascript.

var myString="?specs=f_demo%3a8+GB!!4!!||f_test%3a2+GB!!2!!||f_test%3a4+GB!!3!!||f_demo%3a8+GB!!4!!||f_demo%3a16+GB!!5!!||||Category:Notebooks"

I want to remove all word start with "f_test" and end with "||".

output string like :



Answer Source

Use String#replace method with regex /f_test[^|]+\|\|/g(or /f_test.+?\|\|/g)

var myString = "?specs=f_demo%3a8+GB!!4!!||f_test%3a2+GB!!2!!||f_test%3a4+GB!!3!!||f_demo%3a8+GB!!4!!||f_demo%3a16+GB!!5!!||||Category:Notebooks";

  myString.replace(/f_test[^|]+\|\|/g, '')

UPDATE : If test is loading from a string variable then generate regex using RegExp constructor.

var k = "test",
  myString = "?specs=f_demo%3a8+GB!!4!!||f_test%3a2+GB!!2!!||f_test%3a4+GB!!3!!||f_demo%3a8+GB!!4!!||f_demo%3a16+GB!!5!!||||Category:Notebooks";

  myString.replace(RegExp('f_' + k + '[^|]+\\|\\|', 'g'), '')

Refer : Converting user input string to regular expression

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download