0


I try to extract all text from document title before it gets to closest "|" or "-" or "/" . I assume i have to write something like this but im not good at regex.

var docTitle = document.title();
    docTitle.match(regex);

Can someone help me with correct regex or suggest perhaps a better solution to achieve desired effect ?

Thank you !

6
  • Have you been here: regex101.com ? Commented Jul 27, 2017 at 15:10
  • 1
    "([^|/-]+)" that will match up to the first | or - or / Commented Jul 27, 2017 at 15:10
  • @ganga Can you provide an example Commented Jul 27, 2017 at 15:12
  • post a string/data how title looks like and how it should look Commented Jul 27, 2017 at 15:12
  • 2
    @sniperd Remember to escape the forward slash, or things may not go as expected. Commented Jul 27, 2017 at 15:13

1 Answer 1

2

Use var shortTitle = document.title.split(/[|\/-]/,1)[0];

The split function divides a string into an array based on a separator.

You can pass a Regular Expression object into the split function if the separator is a pattern and not constant.

The regular expression is [|/-] meaning any |, /, or -. The / needed to be escaped with a \ in JavaScript because / is also the character that delimits Regular Expression literals.

The first element of the split array ([0]) will be the document title before the first occurrence of any of those separator characters.

It will be the only element in the array, because we told the split function to stop after the first occurrence.

If the document title contains no matching characters to split on, the split function returns the whole string in the first array element, anyway.

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

4 Comments

@Gangnus, What do you mean? That's not even valid RegEx, JavaScript gives me Uncaught SyntaxError: Invalid regular expression flags
\s*[|\/-]\s* Sorry, html changed what I have written. I mean, parts of title could have spaces on sides
I see, we only need to eliminate any whitespace before the separator, which would only need \s*[|\/-]. The question didn't mention that, but it wouldn't be unreasonable.
It can be any way. Your regex is correct. I only think that if we can delete border spaces from header details on this stage, it is better than to use trim() afterwards.

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.