Let's say I have a string like this:
...hello world.bye
But I want to remove the first three dots and replace .bye
with !
So the output should be
hello world!
it should only match if both conditions apply ( ...
at the beginning and .bye
at the end)
And I'm trying to use js replace method. Could you please help? Thanks
Your regex would be
const rx = /\\.\\.\\.([\\s\\S]*?)\\.bye/g const out = '\\n\\nfoobar...hello world.bye\\nfoobar...ok.bye\\n...line\\nbreak.bye\\n'.replace(rx, `$1!`) console.log(out)
In English, find three dots, anything eager in group, and ending with .bye.
The replacement uses the first match $1
and concats !
using a string template.
First match the dots, capture and lazy-repeat any character until you get to .bye
, and match the .bye
. Then, you can replace with the first captured group, plus an exclamation mark:
const str = '...hello world.bye'; console.log(str.replace(/\\.\\.\\.(.*)\\.bye/, '$1!'));
The lazy-repeat is there to ensure you don't match too much, for example:
const str = `...hello world.bye ...Hello again! Goodbye.`; console.log(str.replace(/\\.\\.\\.(.*)\\.bye/g, '$1!'));
You don't actually need a regex to do this. Although it's a bit inelegant, the following should work fine (obviously the function can be called whatever makes sense in the context of your application):
function manipulate(string) {
if (string.slice(0, 3) == "..." && string.slice(-4) == ".bye") {
return string.slice(4, -4) + "!";
}
return string;
}
(Apologies if I made any stupid errors with indexing there, but the basic idea should be obvious.)
This, to me at least, has the advantage of being easier to reason about than a regex. Of course if you need to deal with more complicated cases you may reach the point where a regex is best - but I personally wouldn't bother for a simple use-case like the one mentioned in the OP.
An arguably simpler solution:
const str = '...hello world.bye'
const newStr = /...(.+)\.bye/.exec(str)
const formatted = newStr ? newStr[1] + '!' : str
console.log(formatted)
If the string doesn't match the regex it will just return the string.
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.