Kalpesh Boghara
Kalpesh Boghara

Reputation: 461

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!

Upvotes: 0

Views: 688

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

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

Upvotes: 1

Related Questions