1

I have a string something like this

Material TD Vandal High Supreme Signal Blue / University Red-B

I want to add hyphen, so final string becomes

Material TD Vandal High Supreme Signal - Blue / University Red-B

Hyphen should be added word before first / string can have multiple /

i tried string.replace(/([A-Za-z][ ][/])/g, '-$1');

tried few more things, but nothing is working.

1
  • Try .replace(/[A-Za-z]+\s+\//, "- $&"), see this regex demo Commented Oct 16, 2018 at 17:27

1 Answer 1

2

When you say Hyphen should be added word before first /, the question is why did you use /g modifier? g means "global", it will try to find all non-overlapping occurrences of the regex match in the string. You do not need that modifier in the first place.

Second, [A-Za-z] matches a single char. Since the regex engine matches strings from left to right, the letter that is matched with this pattern should be followed with a space and then a slash, hence, it will match e /, not Blue /. To match a whole word, you will need to add a + quantifier after [A-Za-z]. You might also just use \w if you do not care if those are letters or digits (or _). Even \S+, one or more non-whitespaces will work.

To keep it close to the original, I suggest:

var result = string.replace(/[A-Za-z]+\s+\//, "- $&");

See the regex demo.

Details

  • [A-Za-z]+ - 1 or more ASCII letters
  • \s+ - 1+ whitespaces
  • \/ - a / char (escaped because it is used in a regex literal).

The $& in the replacement pattern is the replacement backreference that refers to the whole match, no need wrapping the whole pattern with a capturing group.

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

Comments

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.