Reputation: 2683
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
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'));
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