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!

2
  • What've you attempted or tried? Commented Jul 19, 2016 at 5:45
  • Where is code what you have tried to remove the desired string Commented Jul 19, 2016 at 5:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
@KalpeshBoghara : glad to help... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.