I'm trying to remove whitespace from an argument passed by a HTML form into a function using the trim() method. The function then lists the addresses that match that postcode.
var postCodes = {
N48LP: {
address: ['59, White Gardens', '54, White Gardens', '52, White Gardens', '55, White Gardens']
}
};
function searchCode(arg2){
arg2.trim();
if(typeof postCodes[arg2] === 'undefined') {
document.getElementById('oldpa').innerHTML = 'Postcode not found';
} else {
// code here which prints the list of addresses
}}};
This doesn't work. Where 'N48LP' works, 'N4 8LP' or 'N 48LP' will result in 'Postcode not found'. Could anyone tell me why? Many thanks.
Try replace instead of trim.
arg2.replace(/\s+/, "");
you are looking for: arg2.split(' ').join(''). trim function remove spaces from start and from end of strings only
There are several problems in your code. One is that trim() does not trim the string in-place, this means that it does not mutate the original string. The second one is that trim() does not remove spaces in between characters.
To solve this, you can use replace() with a regex that replaces all occurence of all spaces as empty strings, and then assign such value as an index to be used when checking the postCodes object.
var postCodes = {
N48LP: {
address: ['59, White Gardens', '54, White Gardens', '52, White Gardens', '55, White Gardens']
}
};
function searchCode(arg2) {
// note that you have to make the regex to perform
// a global search to make it function as a trim as well
var index = arg2.replace(/\s+/g, '');
if (typeof postCodes[index] === 'undefined') {
document.getElementById('oldpa').innerHTML += 'Postcode not found';
} else {
// code here which prints the list of addresses
document.getElementById('oldpa').innerHTML += [
'<strong>input: ', arg2.replace(/\s+/g, ' '), '</strong>',
'<pre>', JSON.stringify(postCodes[index], 0, 4), '</pre>'
].join('');
}
}
searchCode('N 48LP');
searchCode(' N48LP ');
searchCode(' N 4 8 L P ');
<div id="oldpa"></div>
Problem is here arg2.trim();. As #DontRelaX said trim() methods does not remove white spaces in the middle of the string. And another problem, considering that this would be a problem, that trim() returns modified string, but does not effect the value of the sting itself.
Related
I'm trying to replace all "WUB" in a string with a blank space. The problem is, if I have 2 "WUB" in a row, it will return 2 blank spaces. How do only return 1 blank space if I have "WUBWUB"?
function songDecoder(song) {
var replacedLyrics = song.replace(/#|WUB/g,' ');
return replacedLyrics;
}
Try this regex /(WUB)+/g it will match 1 or more element in the parenthesis
function songDecoder(song)
{
var replacedLyrics = song.replace(/(WUB)+/g,' ');
return (replacedLyrics);
}
console.log(songDecoder("hello world !"));
console.log(songDecoder("WUB"));
console.log(songDecoder("helloWUBWUBworldWUB!"));
/#|WUB/g should be /#|(WUB)+/g for your purpose. Do you also want to replace multiple "#"s with a single space. Then you might want /(#|WUB)+/g
The parentheses group the target strings together, then plus seeks one or more repetition of the group.
If you don't want a space at the beginning or end of your string, that could be another regex function, but probably the most straightforward method is to use the .trim() function. So:
alert(
songDecoder('WUBYOUREWUBWELCOMEWUB')
)
function songDecoder(song) {
var replacedLyrics = song.replace(/(#|WUB)+/g,' ').trim();
return replacedLyrics;
}
Change your code to .replace(/#|(WUB)+/g, " ");.
This searches for as many "WUB's" in a row before replacing them with a blank space
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 using an ES6-like variable formatting with the syntax of ${varName}, and while processing them I'm trying to enumerate all unique variables specified, using the following code:
function enumVars(txt) {
var v, names = [];
var reg = /\$\{\s*[a-zA-Z\$_][a-zA-Z0-9\$_]*\s*}/g;
while (v = reg.exec(txt)) {
var svn = v[0].replace(/???/, ''); // stripped variable name;
if (names.indexOf(svn) === -1) {
names.push(svn);
}
}
return names;
}
I haven't been able to figure out the correct RegExp for stripping the variable name from the exec result.
When I use v[0], it gives me ${varName} string, and I need to strip it into just varName, removing leading ${, trailing }, and all white spaces that may reside inside { } around the variable.
The variable is expected to follow the javascript naming convention, which means:
a valid variable starts with a letter, underscore or '$' symbol, followed by any combination of letters, digits, underscores or '$';
leading and trailing spaces around the variable are to be ignored.
In all, we may have a variable returned from exec as ${ _$abc12_$ }, and I need a RegExp for calling replace that would return just _$abc12_$.
Thanks everyone for helping!
Your replace regexp could be
/^\$\{\s*|\s*}$/g
In English, this says "remove both ${... at the beginning, or ...} at the end.
It could be slightly easier to just grab all the strings, and transform them all at once, then filter out duplicates:
function enumVars(txt) {
return txt
// Find all matches of form ${var}
. match(/\$\{\s*[a-z$_][a-z0-9$_]*\s*}/gi)
// Strip off ${ and }, yielding just variable name
. map(function(v) { return v.replace( /^\$\{\s*|\s*}$/g, ''); })
// Filter out duplicates
. filter(function(v, i, a) { return a.indexOf(v) === i; });
}
I'm working on a text input for the backend of a website. I want a couple things to be automatically corrected. Example, new lines in the textarea I convert to <br>. I also want to let the user tab over on new lines.
This requires changing spaces over to . I only want to convert spaces that are at the start of a new line though. Example, say the user types this into a textarea:
This is my text! It's pretty great.
This is a second line.
This is a third line, that is indented by four spaces.
This is a fourth line.
Using regex, I've gotten the first space on each line to convert:
.replace(/^[ ]/mg,' ');
I've gotten multiple spaces to convert to one space:
.replace(/[ ]{2,}/mg,' ');
I can't figure out how to convert all four of those indenting spaces though. I've been scouring the internet for about 3 hours, and I've found similar answers, but nothing that I could get to work here. Any thoughts?
function escapeSpaces(str) {
var regex = /^ +/mg;
return str.replace(regex, function (match) {
var result = "";
for (var i = 0, len = match.length; i < len; i++) {
result += " ";
}
return result;
});
}
This may not be the best solution, but it works.
Alternatively:
function escapeSpaces (str) {
return str.replace(/^ +/mg, function (match) {
return match.replace(/ /g, " ");
});
}
I'm trying to insert some whitespace in a string if the string conforms to a certain format. Specifically, if the string consists of only numbers, and is exactly five characters in length, whitespace should be added between the third and fourth numbers.
Here's my test case:
function codeAddress() {
var num_regex = /^\d+$/,
input = $("#distributor-search").val(),
address = (input.match(num_regex) && input.length == 5) ? input.split('').splice(3, 0 , ' ').join() : input ;
console.log('The address is: ' + address);
return false;
}
For some reason, chaining .split(), .splice() and .join() seems to not return anything. Where am I going wrong?
split() returns an array, splice() returns the array with the removed elements and join() returns the joined array like they should.
Looks like everything goes wrong at splice(). Instead of giving the remainders, you get the removed items.
My test:
var input = '123,789';
var output = input.split(',').splice(1, 0, '456').join(',');
console.log(output); // outputs nothing, because `splice(1, 0, '456')` doesn't remove any values
You could solve this by making a prototype that uses splice's functionality, like so:
Array.prototype.isplice = function() {
var tmp = this;
Array.prototype.splice.apply(tmp, Array.prototype.isplice.arguments);
return tmp;
};
var output = input.split(',').isplice(1, 0, '456').join(',');
console.log(output); // outputs ["123", "456", "789"] as expected
As others have explained, your function didn't work because .splice() returns the removed elements, instead of the resulting array.
Try using this regex, instead:
/^(\d\d\d)(\d\d)$/
It will only match a string if it's 5 digits long, it won't modify other strings.
Examples:
var s = '123456'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123456"
var s = '1234'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "1234"
var s = '12345'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123 45"
So, in your case:
address = $("#distributor-search").val().replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
Why not just use the regex itself?
var num_regex = /^(\d\d\d)(\d\d)$/,
input = $("#distributor-search").val(),
address = input.match(num_regex);
if (address) address = address[1] + ' ' + address[2];
That regex matches a five-digit string and groups the first three and last two digits together. If the test string matches, then the .match() function returns an array with the two groups in positions 1 and 2 (position 0 being the entire match).
You can't concatenate splice with join in your case:
splice(3, 0 , ' ').join()
remember that splice returns a new array containing the removed items, not the result array.