Javascript Regex For Comma Delimited String - javascript

I need a regex expression that performs a "contains" function on a input/type=hidden field's value. This hidden field stores unique values in a comma delimited string.
Here's a scenario.
The value: "mix" needs to be added to the hidden field. It will only be added if it does not exist as a comma delimited value.
With my limited knowlege of regex, I can't prevent the search from returning all ocurrences of the "mix" value. For example if: hiddenField.val = 'mixer, mixon, mixx', the regex always returns true, because the all three words contain the "mix" characters.
Thanks in advance for the help

You can use \b metacharacter to set word boundaries:
var word = "mix";
new RegExp("\\b" + word + "\\b").test(hidden.value);
DEMO: http://jsfiddle.net/ztYff/
UPDATE. In order to protect our regular expression of possible problems when using variable instead of hardcoding (see comments below), we need to escape special characters in word variable. One possible solution is to use the following method:
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
DEMO: http://jsfiddle.net/ztYff/1/
UPDATE 2. Following #Porco's answer we can combine regular expressions and string splitting to get another universal solution:
hidden.value.split(/\s*,\s*/).indexOf(word) != -1;
DEMO: http://jsfiddle.net/ztYff/2/

hiddenField.val.split(',').indexOf('mix') >= 0
Could also use a regex(startofstring OR comma + mix + endofstring OR comma):
hiddenField.val.match(/(,|^)mix($|,)/)

hiddenField.val.match(/^(mix)[^,]*/);

How about:
/(^|,)\s*mix\s*(,|$)/.test(field.value)
It matches mix, either if it is at the beginning of a string or at the end or in between commas. If each entry in the list can consist of multiple words, you might want to remove the \s*.

Related

regex custom lenght but no whitespace allowed [duplicate]

I have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:
var regexp = /^\S/;
This works for me if there are spaces between the characters. That is if username is ABC DEF. It doesn't work if a space is in the beginning, e.g. <space><space>ABC. What should the regex be?
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
Use + plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex #Bergi mentioned just the string version for new RegExp constructor
This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g
This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.
/^([A-z0-9!##$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/
Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.
If you want just alphanumeric characters then change what is in the [] like so:
/^([A-z])*[^\s]\1*$/

Capture quoted string in comma separated string using regular expression

I am trying to match all the string withing double quotes which is separated by comma
For eg in the sample string
"COUNT","count(1)","crmuser.accounts"
i want to match
COUNT
count(1)
crmuser.accounts
Regular expression (?<=").*?(?=") is matching the comma seperator as well which is not required. How can i exclude commas in the string.
There are a few different workarounds you could use for this; for example using capture groups as suggested in the comments by The fourth bird. But for me personally, I try to avoid using .*.
For this type of example, I would honestly recommend just using a character set of valid characters you will use and looking for more than one character (2 or more) because you will effectively skip lone separators such as a single ,. You can even add a comma to that character set and it will still work.
(?<=")[\w\(\)\.,]{2,}(?=")
Demo
For this format of string you could just use :
var str = '"COUNT","count(1)","crmuser.accounts"' ;
var separated = str.split('","') ;
for(var i in separated){
i.replace('"','') ;
} ;

Replace multiple spaces, multiple occurrences of a comma

I am trying to clean an input field client side.
Current Value
string = 'word, another word,word,,,,,, another word, ,,;
Desired Value after cleaning
string = 'word,another word,word,another word;
Simplified version of what I have tried http://jsfiddle.net/zg2e7/362/
You can use
var str = 'word,word,word,,,,,new word, , another word';
document.body.innerHTML = str.replace(/(?:\s*,+)+\s*/g, ',');
You need to use g modifier to find and replace all instances
You need to also match optional whitespace between commas and on both sides of them.
Regex explanation:
(?:\s*,+)+ - 1 or more sequences of
\s* - 0 or more whitespace characters
,+ - 1 or more commas.
string = 'word, another word,word,,,,,, another word, ,,';
console.log(string.replace(/(,)[,\s]+|(\s)\s+/g ,'$1').replace(/^,|,$/g,''));
Try using split and trim and map and join rather than regex being that regex can be a bit clunky.
$.map(str.split(','),function(item,i){
if(item.trim()){
return item.trim()
}
}).join(',')
So split the string by the , and then use the map function to combine them. If the item has value after being trimmed then keep the value. Then after it has been mapped to a array of the valid values join them with a comma.

Replacing second part of string with Javascript and replace()

I need to replace any occurrence of a sequence of integers followed by a dash and then another sequence of integers, with only the first sequence of integers. For example:
THIS IS A STRING 2387263-1111 STRING CONTINUES
Will become:
THIS IS A STRING 2387263 STRING CONTINUES
Can I use that with Javascript and replace()?
You can do:
str = str.replace(/(\d+)-\d+/,'$1');
See it
Which replaces a group of digits followed by a hyphen followed by a group of digits with the first group of digits.
If you want to replace multiple occurrences of such pattern just use the g modifier as:
str = str.replace(/(\d+)-\d+/g,'$1');
NEW ANSWER -
Yes, in your case according to me, first you need to match that whole string "2387263-1111" using a regex and then remove that part followed by '-' and then replace the result in the original string.
Check the answer from codaddict. Mine would've almost been same but his answer seems more appropriate.
OLD ANSWER: -
Why replace? Just use split and get the first value.
var str = "2387263-1111";
var output = str.split("-")[0];
User RegExp function of javascript
str = str.replace(new RegExp("-[0-9]+"), " ");
Not really a new answer, just an addition to codaddict. Don't know JScript's regex
all that well, but I asume it uses extended regular expressions (if not, forget this).
If you need validation on boundry conditions you could do something like this:
str = str.replace( /((^|\s)\d+)-\d+(?=\s|$)/g, '$1' );
That would prevent matching this type of thing:
A STRING 2387263-1111STRING CONTINUES
A STRING2387263-1111 STRING CONTINUES
A STRING2387263-1111STRING CONTINUES

Javascript split regex question

hello I am trying what I thought would be a rather easy regex in Javascript but is giving me lots of trouble.
I want the ability to split a date via javascript splitting either by a '-','.','/' and ' '.
var date = "02-25-2010";
var myregexp2 = new RegExp("-.");
dateArray = date.split(myregexp2);
What is the correct regex for this any and all help would be great.
You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:
date.split(/[.,\/ -]/)
Although dashes have special meaning in character classes as a range specifier (ie [a-z] means the same as [abcdefghijklmnopqrstuvwxyz]), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.
To explain why your pattern didn't work, /-./ tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".
or just (anything but numbers):
date.split(/\D/);
you could just use
date.split(/-/);
or
date.split('-');
Say your string is:
let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;
You want to split the string by the following delimiters:
Colon
Semicolon
New line
You could split the string like this:
let rawElements = str.split(new RegExp('[,;\n]', 'g'));
Finally, you may need to trim the elements in the array:
let elements = rawElements.map(element => element.trim());
Then split it on anything but numbers:
date.split(/[^0-9]/);
or just use for date strings 2015-05-20 or 2015.05.20
date.split(/\.|-/);
try this instead
date.split(/\W+/)

Categories

Resources