Patrik Krehák
Patrik Krehák

Reputation: 2683

Match exact string or first word with Regex in Javascript

My goal is to match first word of a string. So when you have string like "Testing line", it would return "Testing" as first word and I can do whatever I want with it. This is what I already have:

elm.html(elm.text().replace(/([^\s]+)/, '<span class="first-word">$1</span>'));

I have element with text "Demo web" and it returned "<span class="first-word">Demo</span> web". So this is OK.

BUT

I also want one exception, when part of string contains "Admin", it would return just that part. What I want to say...

Input: Adminer helps -> <span class="first-word">Admin</span>er helps

I tried this regex: ([Admin|^\s]+) which work OK, but only for this case. It now doesn't work on everyhing else, where "Admin" is not present. Example:

Input: Blabla date -> Blabla<span class="first-word"> d</span>ate

What am I doing wrong? I want to do it just with regex, if it is possible.

Upvotes: 1

Views: 1230

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

You can use regex /\bAdmin|\S+/

function replaceText(str) {
  return str.replace(/\bAdmin|\S+/, '<span class="first-word">$&</span>');
}

console.log(replaceText('Adminer help'));
console.log(replaceText('abc help'));
console.log(replaceText('test help'));

Regex explanation here

Regular expression visualization


FYI : [Admin|^\s]+ is a "character class" that match a single character present in the list. In your case the first match is d it will replace d. Also ^ will only works if it's in the beginning otherwise it will act as character.

Upvotes: 4

Related Questions