.replace not replacing all chars [NODEJS] - javascript

I've searched all around the web for a response to this question,
Why do my .replace only replace chars that doesnt have any other char behind
My code is :
const fixedstring = string.replace('&', '^&')
When i enter : &notepad.exe& has a string, it give me the output ^&notepad.exe& instead of ^&notepad.exe^&
Can someone help me ? (i've tried the /g)
Thanks for the guy that will help me or just read my post, thanks !

You can't use the global flag /g unless you are using regex to find the characters to replace. You are currently using a string to find, which will only match the first instance.
Instead, use the regex:
.replace(/&/g, "^&")
Here is a working example.
const stringToReplace = "&notepad.exe&"
const replaced = stringToReplace.replace(/&/g, '^&')
console.log(replaced)

Related

regex matching string in between string

I have always found regex hard. I am sorry but I had to ask,
https://meet.google.com/zzz-tssd-trt?authuser=1
https://meet.google.com/zzz-tssd-trt
https://meet.google.com/zzz44-5454ws-fgaf
How would I get the code, for instance zzz44-5454ws-fgaf or zzz-tssd-trt or zzz-tssd-trt from these strings?
No need to use Regex. Much safer to use URL
const paths = `https://meet.google.com/zzz-tssd-trt?authuser=1
https://meet.google.com/zzz-tssd-trt
https://meet.google.com/zzz44-5454ws-fgaf`
.split(/\n/).map(url => new URL(url).pathname)
console.log(paths)
You can use the regex \w(?=/)/([^?|\n]+) this regwx will group all the charctes after the last / and before ? or new line.
import re
s = """
https://meet.google.com/zzz-tssd-trt?authuser=1
https://meet.google.com/zzz-tssd-trt
https://meet.google.com/zzz44-5454ws-fgaf
"""
print(re.findall(r"\w(?=/)/([^?|\n]+)", s))
Output
['zzz-tssd-trt', 'zzz-tssd-trt', 'zzz44-5454ws-fgaf']
'https://meet.google.com/[a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{3}','gi'
this is more restrictive and worked well for me.

regex to remove certain characters at the beginning and end of a string

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
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.
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.
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.

Find file sequence with RegExp in Javascript

I have a simple question:
How do I use RegExp in Javascript to find strings that matches this filter:
*[0-9].png in order to filter out file sequences.
For example:
bird001.png
bird002.png
bird003.png
or
abc_1.png
abc_2.png
Should ignore strings like abc_1b.png and abc_abc.png
I'm going to use it in a getFiles function.
var regExp = new RegExp(???);
var files = dir.getFiles(regExp);
Thanks in advance!
EDIT:
If I have a defined string, let's say
var beginningStr = "bird";
How can I check if a string matches the filter
beginningStr[0-9].png
? And ideally beginningString without case sensitivity. So that the filter would allow Bird01 and bird02.
Thanks again!
Anything followed by [0-9] and ened by .png:
/^.*[0-9]\.png$/i
Or simply without begining (regex will find it itself):
/[0-9]\.png$/i
If I understood correctly, you need a regex that matches files with names which:
Begin with letters a-z, A-Z
Optionally followed with single _
Followed by one or more digits
Ending with .png
Regex for this is [a-zA-Z]_{0,1}+\d+\.png
You could try online regex builders which offer immediate explanation of what you write.
If I understood correctly,
var re = /\s[a-zA-Z]*[0-9]+\.png/g;
var filesArr = str.match(re);
filesArr.sort();// you can use own sort function
Please specify what is the dir variable

Replace all besides the Regex group?

I was given a task to do which requires a long time to do.
The image say it all :
This is what I have : (x100 times):
And I need to extract this value only
How can I capture the value ?
I have made it with this regex :
DbCommand.*?\("(.*?)"\);
As you can see it does work :
And after the replace function (replace to $1) I do get the pure value :
but the problem is that I need only the pure values and not the rest of the unmatched group :
Question : In other words :
How can I get the purified result like :
Eservices_Claims_Get_Pending_Claims_List
Eservices_Claims_Get_Pending_Claims_Step1
Here is my code at Online regexer
Is there any way of replacing "all besides the matched group" ?
p.s. I know there are other ways of doing it but I prefer a regex solution ( which will also help me to understand regex better)
Unfortunately, JavaScript doesn't understand lookbehind. If it did, you could change your regular expression to match .*? preceded (lookbehind) by DbCommand.*?\(" and followed (lookahead) by "\);.
With that solution denied, i believe the cleanest solution is to perform two matches:
// you probably want to build the regexps dynamically
var regexG = /DbCommand.*?\("(.*?)"\);/g;
var regex = /DbCommand.*?\("(.*?)"\);/;
var matches = str.match(regexG).map(function(item){ return item.match(regex)[1] });
console.log(matches);
// ["Eservices_Claims_Get_Pending_Claims_List", "Eservices_Claims_Get_Pending_Claims_Step1"]
DEMO: http://jsbin.com/aqaBobOP/2/edit
You should be able to do a global replace of:
public static DataTable.*?{.*?DbCommand.*?\("(.*?)"\);.*?}
All I've done is changed it to match the whole block including the function definition using a bunch of .*?s.
Note: Make sure your regex settings are such that the dot (.) matches all characters, including newlines.
In fact if you want to close up all whitespace, you can slap a \s* on the front and replace with $1\n:
\s*public static DataTable.*?{.*?DbCommand.*?\("(.*?)"\);.*?}
Using your test case: http://regexr.com?37ibi
You can use this (without the ignore case and multiline option, with a global search):
pattern: (?:[^D]+|\BD|D(?!bCommand ))+|DbCommand [^"]+"([^"]+)
replace: $1\n
Try simply replacing the whole document replacing using this expression:
^(?: |\t)*(?:(?!DbCommand).)*$
You will then only be left with the lines that begin with the string DbCommand
You can then remove the spaces in between by replacing:
\r?\n\s* with \n globally.
Here is an example of this working: http://regexr.com?37ic4

Is it possible to cut off the beginning of a string using regex?

I have a string which contains a path, such as
/foo/bar/baz/hello/world/bla.html
Now, I'd like to get everything from the second-last /, i.e. the result shall be
/world/bla.html
Is this possible using a regex? If so, how?
My current solution is to split the string into an array, and join its last two members again, but I'm sure that there is a better solution than this.
For example:
> '/foo/bar/baz/hello/world/bla.html'.replace(/.*(\/.*\/.*)/, "$1")
/world/bla.html
You can also do
str.split(/(?=\/)/g).slice(-2).join('')
> '/foo/bar/baz/hello/world/bla.html'.match(/(?:\/[^/]+){2}$/)[0]
"/world/bla.html"
Without regular expression:
> var s = '/foo/bar/baz/hello/world/bla.html';
> s.substr(s.lastIndexOf('/', s.lastIndexOf('/')-1))
"/world/bla.html"
I think this will work:
var str = "/foo/bar/baz/hello/world/bla.html";
alert( str.replace( /^.*?(\/[^/]*(?:\/[^/]*)?)$/, "$1") );
This will allow for there being possibly only one last part (like, "foo/bar").
You can use /(\/[^\/]*){2}$/ which selects a slash and some content twice followed by the end of the string.
See this regexplained.

Categories

Resources