Kalpesh Boghara Kalpesh Boghara - 4 months ago 25
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 :

?specs=f_demo%3a8+GB!!4!!||f_demo%3a8+GB!!4!!||f_demo%3a16+GB!!5!!||||Category:Notebooks"


Thanks!

Answer

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";

console.log(
  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";

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

Refer : Converting user input string to regular expression