0

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!

Kalpesh Boghara
  • 418
  • 3
  • 22

1 Answers1

1

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

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • If i want like this then 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"; var k="test"; myString= myString.replace(/f_@k[^|]+\|\|/g, '') What about k? – Kalpesh Boghara Jul 19 '16 at 06:08
  • @KalpeshBoghara : glad to help... :) – Pranav C Balan Jul 19 '16 at 06:16