REGEX: Appending Single Space between Capitals in Javascript - javascript

I got some idea from a C# related thread, but I need it in Javascript. I am try all sorts of things, it doesn't seem to work.
name.replace(/[A-Z]/g, / $&/);
What I am trying to do is make:
FirstName
with spaces:
First Name
But what I get is:
/ F/irst/ N/ame
Any ideas would be much appreciated.

"FirstName".replace(/([a-z])([A-Z])/g, '$1 $2')
That results in
First Name
Without a leading space.

s.replace(/[A-Z]/g, ' $&')
The second parameter need not be a regex, but a string instead.

Remove the / from the replace section. Some languages need them, some don't.

Related

How do I replace string within quotes in javascript?

I have this in a javascript/jQuery string (This string is grabbed from an html ($('#shortcode')) elements value which could be changed if user clicks some buttons)
[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="visualizer_plugin" path="map"
source_files="bundeslander_staple.csv" include cols="1,2,4" exclude cols="3"]
In a textbox (named incl_sc) I have the value:
include cols="2,4"
I want to replace include_cols="1,2,4" from the above string with the value from the textbox.
so basically:
How do I replace include_cols values here? (include_cols="2,4" instead of include_cols="1,2,4") I'm great at many things but regex is not one of them. I guess regex is the thing to use here?
I'm trying this:
var s = $('#shortcode').html();
//I want to replace include cols="1,2,4" exclude cols="3"
//with include_cols="1,2" exclude_cols="3" for example
s.replace('/([include="])[^]*?\1/g', incl_sc.val() );
but I don't get any replacement at all (the string s is same string as $("#shortcode").html(). Obviously I'm doing something really dumb. Please help :-)
In short what you will need is
s.replace(/include cols="[^"]+"/g, incl_sc.val());
There were a couple problems with your code,
To use a regex with String.prototype.replace, you must pass a regex as the first argument, but you were actually passing a string.
This is a regex literal /regex/ while this isn't '/actually a string/'
In the text you supplied in your question include_cols is written as include cols (with a space)
And your regex was formed wrong. I recomend testing them in this website, where you can also learn more if you want.
The code above will replace the part include cols="1,2,3" by whatever is in the textarea, regardless of whats between the quotes (as long it doesn't contain another quote).
First of all I think you need to remove the quotes and fix a little bit the regex.
const r = /(include_cols=\")(.*)(\")/g;
s.replace(r, `$1${incl_sc.val()}$3`)
Basically, I group the first and last part in order to include them at the end of the replacement. You can also avoid create the first and last group and put it literally in the last argument of the replace function, like this:
const r = /include_cols=\"(.*)\"/g;
s.replace(r, `include_cols="${incl_sc.val()}"`)

Why would the replace with regex not work even though the regex does?

There may be a very simple answer to this, probably because of my familiarity (or possibly lack thereof) of the replace method and how it works with regex.
Let's say I have the following string: abcdefHellowxyz
I just want to strip the first six characters and the last four, to return Hello, using regex... Yes, I know there may be other ways, but I'm trying to explore the boundaries of what these methods are capable of doing...
Anyway, I've tinkered on http://regex101.com and got the following Regex worked out:
/^(.{6}).+(.{4})$/
Which seems to pass the string well and shows that abcdef is captured as group 1, and wxyz captured as group 2. But when I try to run the following:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
to replace those captured groups with "" I receive an empty string as my final output... Am I doing something wrong with this syntax? And if so, how does one correct it, keeping my original stance on wanting to use Regex in this manner...
Thanks so much everyone in advance...
The code below works well as you wish
"abcdefHellowxyz".replace(/^.{6}(.+).{4}$/,"$1")
I think that only use ()to capture the text you want, and in the second parameter of replace(), you can use $1 $2 ... to represent the group1 group2.
Also you can pass a function to the second parameter of replace,and transform the captured text to whatever you want in this function.
For more detail, as #Akxe recommend , you can find document on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace.
You are replacing any substring that matches /^(.{6}).+(.{4})$/, with this line of code:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
The regex matches the whole string "abcdefHellowxyz"; thus, the whole string is replaced. Instead, if you are strictly stripping by the lengths of the extraneous substrings, you could simply use substring or substr.
Edit
The answer you're probably looking for is capturing the middle token, instead of the outer ones:
var str = "abcdefHellowxyz";
var matches = str.match(/^.{6}(.+).{4}$/);
str = matches[1]; // index 0 is entire match
console.log(str);

regex - How do I exclude "%" and "_"?

Im allowing numbers, letters, and special characters except for % and _ in my html textbox. I have the pattern /[a-zA-Z0-9!##$^&*()-+=]/. I think its not the best way to do it because I have to list all special characters except the two mentioned. Is there a way in which I don't have to list all special characters and don't include the two mentioned? BTW, Im using javascript regex.
For the demo please see http://jsfiddle.net/ce8Th/
Please help.
There's no need for that complex loop. Just call replace directly on the whole string:
$(this).val(function (i, v) {
return v.replace(/%|_/g, '');
});
Here's your fiddle: http://jsfiddle.net/ce8Th/1/
You could just do the reverse:
/[%_]/
if (pattern.test( ....
It's also nice to not use regex if you don't have to, not that it makes a big difference in this case:
if ("%_".split().indexOf(text.charAt(i)) > -1) {
A white list is always best. I would recommend keeping what you have except adding a length modifier and start and end characters:
/^[a-zA-Z0-9!##$^&*()-+=]+$/
Would I happen to be corrent in guessing that you are using this user input for a MySQL query involving LIKE to search for partial matches?
If so, don't exclude characters. Instead, escape them on the server-side. For instance:
$output = str_replace(Array("%","_"),Array("\\%","\\_"),$input);

Regular Expression in Javascript for finding parameters

I'm trying to write a regular expression in javascript to catch all named parameters in PostgreSQL string to put them in table
lets say we have
var query="SELECT table.data FROM table JOIN table2 ON table2.id=table.id_tab2 WHERE table2.field <> :parm1::int GROUP BY table.data HAVING table.data position(:docType::text in document_type) <> 0
var tab=new Array();
//
I need rs to put into tab all parameters: "param1::int" and "docType::text"
I tried do it myself but with no success :(
http://regexr.com?31nok
something like this? :(\w+::\w+)
and (:[a-zA-Z0-9]+::[a-zA-Z0-9]+)
There can be weird things between a-Z, so just use [a-z] with case insensitive or [a-zA-Z]. I think you probably want a global match (find all results). Multi-line is something else, it makes . match \n which doesn't help you that I can see. Try this: http://regexr.com?31not
I don't know postgreSQL, but I think I got the gist of your question.
Is this correct: http://refiddle.com/2tc?
when i try :([^: ]+::[^: ]+) and (:[^: ]+::[^: ]+) i see no difference- colon is in match in both casec.
However i found some other way
(?!:)([a-z0-9_-]+::[a-z0-9_-]+)
works perfectly.
first part (?<=:) determine "Matches a group before your main expression without including it in the result."
Thanks you all for your answers ;)

Javascript regex to match a person's height

I need a javascript regex pattern to match a person's height to check if the input is valid. Here are some sample input:
5' 9"
6'
5'8"
Any ideas?
If you want to make sure that no one mucks around with it, you could limit it to sensible ranges, eg: 3' to 7'11''
/^(3-7)'(?:\s*(?:1[01]|0-9)(''|"))?$/
I always thought that the "inches" mark was a double quote ("), compared to VonC's answer where he put it as two single quotes (''), so this regex takes both into consideration.
Maybe something like:
^(\d{1,5})\'((\s?)(-?)(\s?)([0-9]|(1[0-1]))\")?$
see: here
Something like:
\d'(?:\s*\d+'')?
The second part refers to optional part of the heigth.
Remove the + if you want only one digit.
\b\d'(?:\s*\d+'')?\b
can also be used to detect that pattern within a text (avoid detecting 1234'45 as an heigth for... a person?!)
You can test that regexp here for javascript.
Ok. Thanks for all your input. Wow, that was fast, Big time.
Anyway, I've tested all your regex and it seems Ruben's answer passed all my test input. Thanks a lot for that mate.
So here's the one that I need:
^(\d{1,5})\'((\s?)(-?)(\s?)([0-9]|(1[0-1]))\")?$
^\d'\s?(\d{1,2}")?$
Tested here: http://www.regular-expressions.info/javascriptexample.html

Categories

Resources