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>
Related
var cartstring = "27,00 - R"
How can I remove spaces and "-" and "R" using only regex (not allowed to use slice etc.)? I need to make strings cartstring1 and cartstring2 which should both be equal to "27,00", first by removing spaces and "-" and "R", and second by allowing only numbers and ",".
cartstring1 = cartstring.replace(/\s/g, "");
cartstring2 = cartstring.replace(/\D/g, "");
Please help me modify these regular expressions to have a working code. I tried to read about regex but still cannot quite get it. Thank you very much in advance.
you can just capture just what you are interested in number and comma:
let re = /[\d,]+/g
let result = "27,00 - R".match(re)
console.log(result)
You can group the characters you want to remove:
var cartstring = "27,00 - R"
let res = cartstring.replace(/(\s|-|R)/g, "")
console.log(res)
Or alternatively, split the string by a space and get the first item:
var cartstring = "27,00 - R"
let res = cartstring.split(" ")[0]
console.log(res)
You are using 2 replacements, one replacing all whitespace chars \s and the other replacing all non digits \D, but note that \D also matches \s so you could omit the first call.
Using \D will also remove the comma that you want to keep, so you can match all chars except digits or a comma using [^\d,]+ in a single replacement instead:
var cartstring = "27,00 - R";
console.log(cartstring.replace(/[^\d,]+/g, ''));
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);
I use
str.replace(/(^,)|(,$)/g, '')
to remove leading and trailing commas.
How can I extend it so I also remove two consecutive commas?
So ,some text,,more text, should become some text,more text?
One way would be to chain with
str.replace(/(^,)|(,$)/g, '').replace(/,,/g, ',')
but then ,some text,,,,more text, will become some text,,more text instead of some text,more text.
Since you appear to be using the str as a source for an array, you can replace all the .replace calls with:
var str = ",some text,,,,more text,";
var resultArray = str.split(',') // Just split the string.
.filter(function(item){ // Then filter out empty items
return item !== '';
});
console.log(resultArray)
No need to worry about leading, trailing or double comma's.
Remove the leading and trailing commas, and then replace multiple consecutive commas by single comma
str.replace(/^,|,$|(,)+/g, '$1');
,+ will match one or more comma, g-global flag to replace all occurrences of it.
var str = ',some text,,more text,';
str = str.replace(/^,|,$|(,)+/g, '$1');
console.log(str);
You may add an alternative branch and enclose it with a capturing group and then use a replace callback method where you can analyze the match groups and perform the replacement accordingly:
var s = ',some text,,,,more text,';
var res = s.replace(/^,|,$|(,+)/g, function(m,g1) {
return g1 ? ',' : '';
});
console.log(res);
To split with commas and get no empty entries in the resulting array, use a simple
console.log(',some text,,,,more text,'.split(',').filter(Boolean));
You could add a positive lookahead with another comma.
var str = ',some text,,more text,';
str = str.replace(/^,|,$|,(?=,)/g, '')
console.log(str);
What about one replace only like: ",some text,,,,more text,".replace(/(^,)|(,$)|,(?=,)/g, '');
[EDIT]
Note that lookbehinds don't work in javascript. so you can only use a lookahead like so.
I am trying to remove some spaces from a few dynamically generated strings. Which space I remove depends on the length of the string. The strings change all the time so in order to know how many spaces there are, I iterate over the string and increment a variable every time the iteration encounters a space. I can already remove all of a specific type of character with str.replace(' ',''); where 'str' is the name of my string, but I only need to remove a specific occurrence of a space, not all the spaces. So let's say my string is
var str = "Hello, this is a test.";
How can I remove ONLY the space after the word "is"? (Assuming that the next string will be different so I can't just write str.replace('is ','is'); because the word "is" might not be in the next string).
I checked documentation on .replace, but there are no other parameters that it accepts so I can't tell it just to replace the nth instance of a space.
If you want to go by indexes of the spaces:
var str = 'Hello, this is a test.';
function replace(str, indexes){
return str.split(' ').reduce(function(prev, curr, i){
var separator = ~indexes.indexOf(i) ? '' : ' ';
return prev + separator + curr;
});
}
console.log(replace(str, [2,3]));
http://jsfiddle.net/96Lvpcew/1/
As it is easy for you to get the index of the space (as you are iterating over the string) , you can create a new string without the space by doing:
str = str.substr(0, index)+ str.substr(index);
where index is the index of the space you want to remove.
I came up with this for unknown indices
function removeNthSpace(str, n) {
var spacelessArray = str.split(' ');
return spacelessArray
.slice(0, n - 1) // left prefix part may be '', saves spaces
.concat([spacelessArray.slice(n - 1, n + 1).join('')]) // middle part: the one without the space
.concat(spacelessArray.slice(n + 1)).join(' '); // right part, saves spaces
}
Do you know which space you want to remove because of word count or chars count?
If char count, you can Rafaels Cardoso's answer,
If word count you can split them with space and join however you want:
var wordArray = str.split(" ");
var newStr = "";
wordIndex = 3; // or whatever you want
for (i; i<wordArray.length; i++) {
newStr+=wordArray[i];
if (i!=wordIndex) {
newStr+=' ';
}
}
I think your best bet is to split the string into an array based on placement of spaces in the string, splice off the space you don't want, and rejoin the array into a string.
Check this out:
var x = "Hello, this is a test.";
var n = 3; // we want to remove the third space
var arr = x.split(/([ ])/); // copy to an array based on space placement
// arr: ["Hello,"," ","this"," ","is"," ","a"," ","test."]
arr.splice(n*2-1,1); // Remove the third space
x = arr.join("");
alert(x); // "Hello, this isa test."
Further Notes
The first thing to note is that str.replace(' ',''); will actually only replace the first instance of a space character. String.replace() also accepts a regular expression as the first parameter, which you'll want to use for more complex replacements.
To actually replace all spaces in the string, you could do str.replace(/ /g,""); and to replace all whitespace (including spaces, tabs, and newlines), you could do str.replace(/\s/g,"");
To fiddle around with different regular expressions and see what they mean, I recommend using http://www.regexr.com
A lot of the functions on the JavaScript String object that seem to take strings as parameters can also take regular expressions, including .split() and .search().
I'm trying to do two things to clean the string, the first is to remove any space and replace it with a comma separator, the second is to remove any non-alphanumeric characters (other than the comma); I have the first part functional, but now I can't figure out how to remove the special characters as well:
$("#fancydiv").keyup(function(e) {
var str = this.value.replace(/(\w)[\s,]+(\w?)/g, '$1,$2');
if (str!=this.value) this.value = str;
});
'?no, special-characters!'.replace(/[^\w,]/g, '')
// => "no,specialcharacters"
[^\w,] will match match non-alphabet, non-digit, non-underscore character excluding a comma.
Try this:
var str = this.value.replace(/\s/g, ',').replace(/[^\w,]/g, '');