How to replace string characters with only one blank space? - javascript

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

Related

How do I replace the last letter of a string element in an array with replace()

I've just started coding..I'm a super beginner and have no idea about regex yet so for now I'd rather not use it. This is an exercise I'm trying to solve. The problem is that when a word contains matching characters, the first character gets the lower case, but what I actually want is the last character of the word to become small.
I don't really require a solution for the problem. Instead I'd rather have some insight on what I'm doing wrong and maybe direct me to the right path :)
function alienLanguage(str) {
let bigWords = str.toUpperCase().split(" ");
let lastLetterSmall = [];
bigWords.forEach(words => {
lastLetterSmall
.push(words
.replace(words
.charAt(words.length -1), words.charAt(words.length -1).toLowerCase()));
});
console.log(lastLetterSmall.join(' '));
}
alienLanguage("My name is John");
alienLanguage("this is an example");
alienLanguage("Hello World");
alienLanguage("HELLO WORLD");
Since you only really want to work with indicies of the string - you don't need to replace anything dynamically other than the last index - replace won't work well, since if you pass it a string, it will only replace the first matching letter. For example:
'foo'.replace('o', 'x')
results in 'fxo', because the first o (and only the first o) gets replaced.
For your code, instead of replace, just concatenate the two parts of the string together: the part from index 0 to next-to-last index, and the character at the last index with toLowerCase() called on it:
function alienLanguage(str) {
const result = str
.toUpperCase()
.split(" ")
.map(line => line.slice(0, line.length - 1) + line[line.length - 1].toLowerCase())
.join(' ');
console.log(result);
}
alienLanguage("My name is John");
alienLanguage("this is an example");
alienLanguage("Hello World");
alienLanguage("HELLO WORLD");

Capitalize the beginning of each sentence

I would like to capitalize the beginning of each sentence. I have the following code from other question:
function applySentenceCase(str) {
return str.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
But if i don't put a dot for a last sentence, it doesn't work properly.
For example: for string "THIS IS THE FIRST QUESTION. SECOND QUESTION" it returns "This is the first question. SECOND QUESTION"
The issue with the regex is the grouping (...)
str.replace(/.+?(?:[.?!]\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Outputs
//"This is the first question. Second question. Third question
Or in es6:
str.replace(/.+?(?:[.?!]\s|$)/g, txt => `${txt.charAt(0).toUpperCase()}${txt.substring(1).toLowerCase()}`);
Changes
[.?!] This is a character class. There is no need to escape characters in a class.
(?:[.?!]\s|$) This matches . or ? or ! followed by a space(\s) OR an end of string $
What is wrong with .+?[\.\?\!](\s|$)
[\.\?\!](\s|$) This one tries to match a . or ? or ! always which is followed by a space or end of sentence. But clearly the last part didn't have one
I don't actually see the need to use regex in this case:
var sentences = "THIS IS THE FIRST QUESTION. SECOND QUESTION";
sentences.split('.').map(function(item) {
var sentence = item.trim();
return sentence.charAt(0).toUpperCase() + sentence.substr(1).toLowerCase();
}).join('. ');
Match against /^.|\.\s*\w/.
The first part says uppercase the first character on the line.
The second part says find a .(end of previous sentence), any amount of white space (\s) followed by 1 alphanumeric character.
Then just replace all of it with an uppercase version.
var str = "this is the first question. second question.";
console.log(str.toLowerCase().replace(/^.|\.\s*\w/ig, function(txt) {
return txt.toUpperCase()
}));
EDIT 1
If you get it in all uppercase, simply call toLowerCase() on the string before replacing.

Remove whitespace from an argument into a JS function

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.

How do you create divs in javascript?

I am given a string as input, and the last letter in every word of the string should be capitalized, and then it is formed into their own div.
The one thing that I am finding tricky is that no matter what the string is there should always be enough divs to be separated, which to me means that I need to have a loop that generates it, which is what I am not sure how to write that logic.
I need this to be the output:
<div>
partY
</div>
<div>
likE
</div>
<div>
itS
</div>
<div>
2015
</div>
This is what I have so far:
function yay (input) {
input = input.toLowerCase().split("").reverse().join("").split(" ");
for(var i = 1 ; i < input.length ; i++){
var len = input[i].length-1;
input[i] = input[i].substring(0, len) + input[i].substr(len).toUpperCase();
}
return input .reverse().join(" ");
}
console.log(yay("Party like its 2015"));
Well, just a few minor changes to your code, which was on the right track... I basically removed the unnecessary reversing and wrapped each word in a div in the loop and viola:
function yay (input) {
input = input.toLowerCase().split(" ");
for(var i = 0 ; i < input.length ; i++){
var len = input[i].length-1;
input[i] = '<div>'+input[i].substring(0, len) + input[i].substr(len).toUpperCase()+'</div>';
}
return input.join("");
}
console.log(yay("Party like its 2015"));
document.write(yay("Party like its 2015"));
Output:
<div>partY</div><div>likE</div><div>itS</div><div>2015</div>
You can use document.createElement('div') and document.createTextNode('text') to simply get what you need.
You can return the content element directly to append to your node of your need, or you can use the innerHTML to do some text manipulations.
EDIT
Modified, I totally missed the last character needs to be uppercase
function yay(str) {
var arr = str.split(' ');
var content = document.createElement('div');
for(var part in arr) {
var sub = document.createElement('div');
var lastChar = arr[part].charAt(arr[part].length-1).toUpperCase();
var appendStr = arr[part].substring(0,arr[part].length-1);
sub.appendChild(document.createTextNode(appendStr+lastChar));
content.appendChild(sub);
}
return content.innerHTML;
}
console.log(yay("Party like its 2015"));
How about this:
function capitalizeLastLetter(input) {
return input.substring(0, input.length - 1) + input.charAt(input.length - 1).toUpperCase();
}
function yay(input) {
return input
.toLocaleLowerCase()
.split(" ")
.map(function(s){ return "<div>" + capitalizeLastLetter(s) + "</div>"; })
.join("");
}
console.log(yay("Party like its 2015"));
document.write(yay("Party like its 2015"));
Remixes this answer on how to capitalize the first letter of a word.
Add newlines where appropriate if you actually need those in your output.
You might want to use String.prototype.replace and feed it with a regular expression:
function yay(input) {
return input.
toLocaleLowerCase().
replace(/([^\s.,:;!?]*)([^\s.,:;!?")])([^\s]*)/g,
function(match, sub1, sub2, sub3) {
return '<div>' + sub1 + sub2.toLocaleUpperCase() + sub3 + '</div>';
});
}
The regex captures zero or more (because regular expressions are "greedy" by default, the algorithm will capture as many characters as it can) non-whitespace (to support alphabets other than Latin) and non-punctuation characters and exactly one non-whitespace/non-punctuation character following them (the last letter in the word, even if it's the only letter forming the word). The last group is zero or more of the previously specified punctuation marks (.,:;!?")). What it says is "non-whitespace character", but the presence of the two previous parenthesized groups implies that it must be a punctuation mark.
The replacement callback here uses four arguments, one (unused in this case) for the entire match and three for submatches corresponding to the parenthesized groups in the regex.
The value returned from the callback replaces the entire match in each successive replacement cycle (abcd in abcd efgh will be replaced with <div>abcD</div> and so on, note that whitespaces will be preserved).
In the callback function, the first submatch consists of all the letters in a word except the last one. It is returned as is, but the other match (which is the last letter) is capitalized. Optionally, a punctuation mark is appended if present in the original input. Everything is then wrapped in the <div> HTML tag and returned.
You can assign the value returned by the yay function to the innerHTML property of an HTML element, for example:
document.querySelector('#container').innerHTML = yay('Party like its 2015');
Spaces present in the input will remain. There is no need to replace them with new line characters, as all whitespaces are treated equally in HTML and will result in the same behavior.
Edit:
Now you can pass input containing punctuation to the function. The following line:
yay('Hello there, how about using some punctuation? "Quote" (Parentheses) ("What?")')
will result in:
'<div>hellO</div> <div>therE,</div> <div>hoW</div> <div>abouT</div> <div>usinG</div> <div>somE</div> <div>punctuatioN?</div> <div>"quotE"</div> <div>(parentheseS)</div> <div>("whaT?")</div>'

Remove (n)th space from string in JavaScript

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().

Categories