1

How can I replace the all the text from ~ to | with regex in javascript ?

test.html~1455551818474|test.html

So far I know how to remove after |

\|.*$

I need to find out how to remove between ~ to |

3
  • 4
    Don't forget to show your attempted code Commented Feb 15, 2016 at 16:25
  • 1
    str = str.replace(/~.*\|/g, '') Commented Feb 15, 2016 at 16:32
  • 1
    @anubhava, please post it as an answer. Commented Feb 15, 2016 at 16:49

2 Answers 2

2

You can use this regex for replacement:

str = 'test.html~1455551818474|test.html';
str = str.replace(/~.*\|/g, '');
//=> test.htmltest.html

If by any chance you want pipe character in output then use:

str = str.replace(/~.*\|/g, '|');
//=> test.html|test.html

Also keep in mind .* is greedy and will find longest match between ~ and | in input in case there are multiple of these.

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

Comments

0

What about:

var str = "test.html~1455551818474|test.html";
var resp = str.replace(/~/g, "|");
console.log(resp);

2 Comments

I will need to remove all the numbers in between though
Why not add that to the question? Do not forget to specify what output you need. Try var resp = str.replace(/~\d*/g, ""); if you need test.html|test.html

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.