I have the following string:
"bar foo test-line drop-line"
I need to replace the words that starts with anything and ends with '-line'.
basically having:
"bar foo new_word new_word"
I tried:
string.replace(/\.-line$/g,'new_word')
but it doesn't work.
Try this as a regex:
/\S+-line(?![-\w])/
The word anchor is not suitable here since dashes are not considered part of a word, so /\\S+-line\\b/
would mistakenly match text-with-line-not-to-be-replaced
. Hence the lookahead construct.
Of course, according to your use case, \\S
may seem a little coarse. If your words really only consist of letters then dashes etc, then you can use the normal* (special normal*)*
pattern:
/[a-z]+(-[a-z]+)*-line(?![-\w])/i
(normal: [az]
, special: -
)
(edit: changed the lookahead construct, thanks to @thg435)
In your regular expression, you can use \\b to detect beginning of new words and \\w for "word characters":
"your string".replace(/\b\w+-line\b/g,'new_word')
How about
string.replace(/\b\S+-line\b/g,'new_word')
\\b
Word boundary
\\S
non whitespace
As fge astutely notes, we need a \\b
after line
so we don't catch things ending lines
liner
etc etc etc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.