How to replace double comma with a single comma in javascript - javascript

How can I convert this 2016-01-04 into this 2016-01-04 in JavaScript?
I have a dataset in an array with dates like this:
["x", "2016-01-04", "2016-01-05", "2016-01-06", "2016-01-07", "2016-01-08", "2016-01-09"]
And I want to covert them to:
['x', '2016-01-04', '2016-01-05', '2016-01-06', '2016-01-07', '2016-01-08', '2016-01-09']
I have tried .replace(/"/g, "'")
but I get an error forcastDate_ordered.replace is not a function

See Special Characters (JavaScript) from MSDN
Characters like the speech mark " and single quotation mark ' can be escaped with a backslash \ - this is helpful when they are in strings using speech marks or quotation marks around them.
And to replace the characters, use String.replace
So the final answer as others have stated is
string s = "\"2016-01-04\"";
return s.replace("\"", "'");
(The single quote is not escaped because the string is surrounded by speech marks " - so it doesn't need it)
UPDATE: your question is changed to involve arrays
In which case, you need Array.map
array.map(s => s.replace("\"", "'"));

var endString = startString.replace(/"/g, "'");
Example:
var startString = 'I hate "double" quotes';
var endString = startString .replace(/"/g, "'");
endString = I hate 'double' quotes
or
doubleQuotesReplacer = (startString) => startString .replace(/"/g, "'");

Related

Regex: search speciale character and remove all spaces + breakable charachter

I would like to search for a space OR more spaces before [:?!] and replace it with
here is my code so far working for many situations except:
hello[ SPACES ]?
it should be
hello ?
text.replace(/ ([:?!])/g, " \$1");
Using Capturing Group
For one or more spaces followed by either a :, ? or ! mark. Capture the second part and use it in the replace string.
const str = "Hey ! Are you busy ?";
str.replace(/ +([:?!])/g, " $1");
console.log(str);
const str = 'Hi my name is mahish dino'
const k=str.replace(/\s/g, '`replace this space with any string or integer')
console.log(k)
using str.replace(/\s/g, '') method you can replace the space with any string.

Get double quotes for the searchTerms result query in the URL with Javascript

var searchTerms = escape(jQuery('input#q').val());
var st = searchTerms.trim();
var res = st.replaceAll("TITLE","ti").replaceAll("%20","%20and%20").replaceAll("AUTHOR","au");
I have the above code and need the search term values in double quotes as the result
It gives result URL as : '&query=heartmate%20and%20owens'
But I need it as : '&query="heartmate"%20and%20"owens"'
The simplest way is to map the values to new values before you inject them into the request. But first you need to split the string into its individual terms...
let terms = st.split(' ');
that will return an array of the individual elements of the string, split on a space character,
then you can trim and append the term...
terms.map(term => {
term.trim(); // <-- this removes all of the whitespace characters, including
// space, tab, no-break space, and all the line terminator
// characters, including LF, CR, etc. from the beginning and end
// of the string
return '"' + term + '"';
});
You may find the need to check a condition of term before applying the map, it really depends on what you're doing.
You can use backslash \ to escape your character
var test = " \" \" ";
console.log(test);

concat string using javascript

var str = 'abc 123 hello xyz';
How to concat above string to abc123helloxyz? I tried to trim but it left spaces still between characters. I can't use split(' ') too as the space is not one some time.
You might use a regex successfully. \s checks for the occurences for any white spaced charachters. + accounts for more than once occurences of spaces. and `/g' to check for continue searching even after the first occurences is found.
var str = 'abc 123 hello xyz';
str = str.replace(/\s+/g, "");
console.log(str);
Use a regex.
var newstr = str.replace(/ +/g, '')
This will replace any number of spaces with an empty string.
You can also expand it to include other whitespace characters like so
var newstr = str.replace(/[ \n\t\r]+/g, '')
Replace the spaces in the string:
str = str.replace(" ", "");
Edit: as has been brought to my attention, this only replaces the first occurrence of the space character. Using regex as per the other answers is indeed the correct way to do it.
The cleanest way is to use the following regex:
\s means "one space", and \s+ means "one or more spaces".
/g flag means (replace all occurrences) and replace with the empty string.
var str = 'abc 123 hello xyz';
console.log("Before: " + str);
str = str.replace(/\s+/g, "");
console.log("After: " + str);

Javascript Split Space Delimited String and Trim Extra Commas and Spaces

I need to split a keyword string and turn it into a comma delimited string. However, I need to get rid of extra spaces and any commas that the user has already input.
var keywordString = "ford tempo, with,,, sunroof";
Output to this string:
ford,tempo,with,sunroof,
I need the trailing comma and no spaces in the final output.
Not sure if I should go Regex or a string splitting function.
Anyone do something like this already?
I need to use javascript (or JQ).
EDIT (working solution):
var keywordString = ", ,, ford, tempo, with,,, sunroof,, ,";
//remove all commas; remove preceeding and trailing spaces; replace spaces with comma
str1 = keywordString.replace(/,/g , '').replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(/[\s,]+/g, ',');
//add a comma at the end
str1 = str1 + ',';
console.log(str1);
You will need a regular expression in both cases. You could split and join the string:
str = str.split(/[\s,]+/).join();
This splits on and consumes any consecutive white spaces and commas. Similarly, you could just match and replace these characters:
str = str.replace(/[\s,]+/g, ',');
For the trailing comma, just append one
str = .... + ',';
If you have preceding and trailing white spaces, you should remove those first.
Reference: .split, .replace, Regular Expressions
In ES6:
var temp = str.split(",").map((item)=>item.trim());
In addition to Felix Kling's answer
If you have preceding and trailing white spaces, you should remove
those first.
It's possible to add an "extension method" to a JavaScript String by hooking into it's prototype. I've been using the following to trim preceding and trailing white-spaces, and thus far it's worked a treat:
// trims the leading and proceeding white-space
String.prototype.trim = function()
{
return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
I would keep it simple, and just match anything not allowed instead to join on:
str.split(/[^a-zA-Z-]+/g).filter(v=>v);
This matches all the gaps, no matter what non-allowed characters are in between. To get rid of the empty entry at the beginning and end, a simple filter for non-null values will do. See detailed explanation on regex101.
var str = ", ,, ford, tempo, with,,, sunroof,, ,";
var result = str.split(/[^a-zA-Z-]+/g).filter(v=>v).join(',');
console.info(result);
let query = "split me by space and remove trailing spaces and store in an array ";
let words = query.trim().split(" ");
console.log(words)
Output :
[
'split', 'me', 'by', 'space','and','remove', 'trailing', 'spaces', 'and', 'store', 'in', 'an', 'array'
]
If you just want to split, trim and join keeping the whitespaces, you can do this with lodash:
// The string to fix
var stringToFix = "The Wizard of Oz,Casablanca,The Green Mile";
// split, trim and join back without removing all the whitespaces between
var fixedString = _.map(stringToFix.split(','), _.trim).join(' == ');
// output: "The Wizard of Oz == Casablanca == The Green Mile"
console.log(fixedString);
<script src="https://cdn.jsdelivr.net/lodash/4.16.3/lodash.min.js"></script>

Javascript regex

Currently I have a basic regex in javascript for replacing all whitespace in a string with a semi colon. Some of the characters within the string contain quotes. Ideally I would like to replace white space with a semi colon with the exception of whitespace within quotes.
var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+/g, ":");
alert(stringout);
Thanks
Robin
Try something like this:
var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, ":");
Note that it will break when there are escaped quotes in your string:
"ab \" cd" ef "gh ij"
in javascript, you can easily make fancy replacements with callbacks
var str = '"james \\"bigboy\\" johnson" joe "wendy johnson" tony';
alert(
str.replace(/("(\\.|[^"])*")|\s+/g, function($0, $1) { return $1 || ":" })
);
In this case regexes alone are not the simplest way to do it:
<html><body><script>
var stringin = "\"james \\\"johnson\" joe \"wendy johnson\" tony";
var splitstring = stringin.match (/"(?:\\"|[^"])+"|\S+/g);
var stringout = splitstring.join (":");
alert(stringout);
</script></body></html>
Here the complicated regex containing \\" is for the case that you want escaped quotes like \" within the quoted strings to also work. If you don't need that, the fourth line can be simplified to
var splitstring = stringin.match (/"[^"]+"|\S+/g);

Categories