I am getting this value from DatePicker
var datepickr = 'Jun-29-2011';
I want to replace underscores(-) with space .
I tried this way , but it isn't working
var b = datepickr.replace("-",' ');
Just for reference:
var datepickr = 'Jun-29-2011';
datepickr.replace("-", " "); // returns "Jun 29-2011"
datepickr.replace(/-/, " "); // returns "Jun 29-2011"
datepickr.replace(/-/g, " "); // returns "Jun 29 2011" (yay!)
The difference is the global modifier /g, which causes replace to search for all instances. Note also that - must be escaped as \- when it could also be used to denote a range. For example, /[a-z]/g would match all lower-case letters, whereas /[a\-z]/g would match all a's, z's and dashes. In this case it's unambiguous, but it's worth noting.
EDIT
Just so you know, you can do it in one line without regex, it's just impressively unreadable:
while (str !== (str = str.replace("-", " "))) { }
.replace is supposed to take a regular expression:
var b = datepickr.replace(/-/g,' ');
I'll leave it as an exercise to the reader to research regular expressions to the full.
(The important bit here, though, is the flag /g — global search)
Try this:
var datepickr = 'Jun-29-2011';
var b = datepickr.replace( /-/g, ' ' );
The /g causes it to replace every -, not just the first one.
var b = 'Jun-29-2011'.replace(/-/g, ' ');
Or:
var b = 'Jun-29-2011'.split('-').join(' ');
replace works with regular expressions, like so:
> "Hello-World-Hi".replace(/-/g, " ")
Hello World Hi
try:
var b = datepickr.toString().replace("-",' ');
I suspect that you are trying to replace chars inside a Date object.
Related
I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");
I've got the string variable, containing the folowing text:
var val1="GES3 02R202035 ";
var val2=0;
var val3="06 ";
var val4="03.01.11i";
var val5="";
I want to use RegExp to get the array of values and filter values from trailing spaces also.
/="?([\w\s\.]*)/g helps alot, except trailing spaces, and i'm not sure about other charachters there could be.
So I need something like /="?(.*);/g but it doesn't remove last " and spaces also.
/="?(.*)"?;/g doesn't remove last ", who know why?
Could please anybody help me with this?
Edit:
The expected output is:
GES3 02R202035
0
06
03.01.11i
and empty string here
Edit:
I need this in javascript (node.js) str.match(/?????/);
Edit: With the help of Wiktor Stribiżew and melpomene finally I came to:
(notice lookbehind in regex, it will work in chrome with harmony flag enabled only)
var str =
'var val1="GES3 02R202035 ";\n' +
'var val2=0;\n' +
'var val3="06 ";\n' +
'var val4="03.01.11i";\n' +
'var val5="";\n';
console.log('before:\n' + str);
var parts = str.match(/(?<=="?)[^"]*?(?=\s*"?;)/g);
console.log('parts\n', parts);
The problem with str.match() was that it return array of matches, and I actually need array of groups. The solution was to arrange RegEx to match exactly the result what I need. It became possible with the latest V8 and its support of lookbehind.
var str =
'var val1="GES3 02R202035 ";\n' +
'var val2=0;\n' +
'var val3="06 ";\n' +
'var val4="03.01.11i";\n' +
'var val5="";\n';
console.log('before:\n' + str);
var re = /=\s*(?:([-+]?\d+(?:\.\d+)?)|"([^"]*)")/g;
var parts = [];
var m;
while (m = re.exec(str)) {
var x =
m[1] !== undefined
? Number(m[1])
: m[2].trim()
parts.push(x);
}
console.log('parts\n', parts);
This code extracts the embedded numbers and strings (after a = sign). Numbers (in the format (- | +)? digits (. digits)?, i.e. an optional sign and optional decimal places are accepted) are converted to JS numbers; strings have their contents extracted and trimmed.
It does not support exponential notation (1e2) or backslash escapes in strings.
Using javascript (including jQuery), I’m trying to replace all but the last non-breaking space if multiple words are joined.
For example:
Replace A String of Words with A String of Words
I think you want something like this,
> "A String of Words".replace(/ (?=.*? )/g, " ")
'A String of Words'
The above regex would match all the strings except the last one.
Assuming your string is like this, you can use Negative Lookahead to do this.
var r = 'A String of Words'.replace(/ (?![^&]*$)/g, ' ');
//=> "A String of Words"
Alternative to regex, easier to understand:
var fn = function(input, sep) {
var parts = input.split(sep);
var last = parts.pop();
return parts.join(" ") + sep + last;
};
> fn("A String of Words", " ")
"A String of Words"
Hi all ia m trying to replace all characters of "+" in a string by using the code below:
var findValue = "+";
var re = new RegExp(findValue, 'g');
searchValueParam = searchValueParam.replace(re, " ");
However i recieve this exception:
SyntaxError: Invalid regular expression: nothing to repeat
previously i applied just searchValueParam = searchValueParam.replace("+", " "); but that only replaces the first occurrence, not all.
Any suggestions?
For multiple replacements you need to use regex with the global (g) modifier, however + has a special meaning (the previous item 1 or more times), so it needs to be escaped.
searchValueParam = searchValueParam.replace(/\+/g,' ');
You need to escape the + sign:
searchValueParam.replace(/\+/g, " ");
If you want to keep the code you have, replace
var findValue = '+';
with
var findValue = '\\+';
Plus has a special meaning (quantifier) in a regular expression. This is why we need to escape it with a backslash: \+. However, when you place this in a string, the backslash itself has to be escaped as it has a special meaning in a string. This is how we end up with '\\+'.
In conclusion, this
var re = new RegExp('\\+', 'g')
is equivalent to this
var re = /\+/g;
The following code replaces only one single quote:
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace("'", "\"");
console.log(b);
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace(/'/g, '"');
console.log(b);
Edit: Removed \ as there are useless here.
Need to use regex for this:
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace(/\'/g, "\"");
http://jsfiddle.net/9b3K3/
You can use a global qualifier (a trailing g) on a regular expression:
var b = a.replace(/'/g, '"');
Without the global qualifier, the regex (/'/) only matches the first instance of '.
replaceAll(search, replaceWith) replaces ALL occurrences of search with replaceWith.
Then, make sure you have a string by wrapping one type of qoutes by different type:
"a 'b' c".replaceAll("'", '"')
// result: "a "b" c"
"a 'b' c".replaceAll(`'`, `"`)
// result: "a "b" c"
More about replaceAll
replaceAll (MDN): replaceAll(search, replaceWith)
It's actually the same as using replace() with a global regex(*), merely replaceAll() is a bit more readable in my view.
(*) Meaning it'll match all occurrences.
Example 1 - search with a string
const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'
console.log(p.replaceAll('2020', '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
Example 2 - search with regex
const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'
const regex = /2020/gi
console.log(p.replaceAll(regex, '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
Important(!) if you choose regex:
when using a regexp you have to set the global ("g") flag;
otherwise, it will throw a TypeError: "replaceAll must be called with
a global RegExp".
You can also use a function as replaceWith
In this case, the function will be invoked after the match has been
performed. The function's result (return value) will be used as the
replacement string.
This looks suspiciously like bad JSON, so I suggest using actual array and object literals, then encoding the proper way:
var a = [{'column1':'value0','column2':'value1','column3':'value2'}];
var b = JSON.stringify(a);
Add the g modifier:
var b = a.replace(/'/g, '"');
You can use a RegExp with the global flag g and all quotes will replaced:
var b = a.replace(/'/g, '"');