Remove multiple white space between text - javascript

var s = "Hello! I'm billy! what's up?";
var result = s.split(" ").join();
console.log(result);
Got this result
Hello!,I'm,,billy!,what's,,,,up?
How can i get rid of this annoying extra spaces between string? So it might look like this.
Hello!,I'm,billy!,what's,up?

Use a regular expression to find all the spaces throughout the string and rejoin with a single space:
var s = "Hello! I'm billy! what's up?";
var result = s.split(/\s+/).join(" ");
console.log(result);
You can also do this without using .split() to return a new array and just use the String.replace() method. The regular expression changes just a little in that case:
var s = "Hello! I'm billy! what's up?";
var result = s.replace(/ +/g, " ");
console.log(result);

You want replace and \s+
\s+ Matches multiple white space character, including space, tab,
form feed, line feed.
trim to remove extra white space at the start and end of the string
var s = " Hello! I'm billy! what's up? ";
console.log(s.replace(/\s+/g, " ").trim());

var s = "Hello! I'm billy! what's up?";
var result = s.replace(/\s+/g,' ').trim();
console.log(result);

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
var str = "Hello! I'm billy! what's up?";
str = str.replace(/ +/g, " ");
console.log(str);
var strr = "Hello! I'm billy! what's up?";
strr = strr.replace(/ +/g, " ");
console.log(strr);

Related

Javascript RegExp Allow Spaces Inside Pattern

I need to replace all "*text*" into "<strong>text</strong>"
when passing text = "normal text *words to be bolded* continue normal text" it doesn't work because of the spaces, it works only for single-word text.
wanted result: "normal text <strong>words to be bolded</strong> continue normal text"
result: "normal text *words to be bolded* continue normal text"
I need this function to work for whatever the text is:
function bold(text){
reg = /\*(\w+)\*/g
return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
}
You should allow a set of characters to be there. Right now, you have the sequence of characters fixed.
function bold(text){
reg = /\*([\w\s]+)\*/g
return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
}
You can use the array split method.
const str = "word1 word2 pla pla";
const newStr = [];
str.split(" ").forEach((val) => {
newStr.push(`<strong>${val}</strong> `);
});
console.log(newStr);
I assume that by 'words to be bolded', you are trying to match anything that is not asterisk.
function bold(text){
let reg = /\*([^\*]*)\*/g;
return text.replaceAll(reg, "<strong>$1</strong>")
};
let result = bold("normal1 *bold1 including space!* normal2 *bold2, including space?* normal3");
console.log(result);

How to regex, and add "-" between words?

UPDATED
I been looking around in the old interweb to see if there is any way I can regex this as part of a replace method I'm doing: str.replace(/\w[A-Z]/gm, "-")
thisIsARegex
into this:
this-Is-A-Regex
I tried to mess around on regex101 with matching a \w character followed by [A-Z] but failed.
Any thoughts?
If the first char can't be uppercase:
var str = "thisIsARegex";
str = str.replace(/(?=[A-Z])/g, "-");
console.log(str); // this-Is-A-Regex
If the first char can be uppercase:
var str = "ThisIsARegex";
str = str.replace(/.(?=[A-Z])/g, "$&-");
console.log(str); // This-Is-A-Regex
or
var str = "ThisIsARegex";
str = str.replace(/\B(?=[A-Z])/g, "-");
console.log(str); // This-Is-A-Regex
(Last snippet suggested by #Thomas.)
var s = "thisIsARegex";
s = s.replace(/([A-Z])/g, '-$1').trim();
console.log(s);
Try this one:
you can check regex on this page and make your own tests:
https://regexr.com/
// initial value
let text = "thisIsARegexText";
// select Uppercase characters
let regexPattern = /[^a-z]/g;
// dump temp array
let newText = [];
// go through all characters, find Uppercase and replace with "-UppercaseCharacter"
for(i of text){
newText.push(i.replace(/[^a-z]/g, "-" + i))
}
// assign the result to the initial variable
text = newText.join("");

Remove and replace consecutive characters

I have that content:
ALL EVERYTHING
I want to remove all and get that string: ALL EVERYTHING.
If I use that code:
var str = $("#post_wall_textarea_parent .emojionearea-editor").html(); // I can't use $("#post_wall_textarea_parent .emojionearea-editor").text(); for many reasons
str_ = str.replace(/ /g, " ");
It gives me that: ALL EVERYTHING.
I want to remove more thant one space between two words.
How could I do to get: ALL EVERYTHING instead of ALL EVERYTHING. ?
Thanks.
Use str.replace(/( )+/g, " ");
const str = "ALL EVERYTHING";
const result = str.replace(/( )+/g, " ");
console.log(result);
`Edited as Dimitri's Comment.

How to replace numbers with an empty char

i need to replace phone number in string on \n new line.
My string: Jhony Jhons,jhon#gmail.com,380967574366
I tried this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /[0-9]/g;
var rec = str.trim().replace(regex, '\n').split(','); //Jhony Jhons,jhon#gmail.com,
Number replace on \n but after using e-mail extra comma is in the string need to remove it.
Finally my string should look like this:
Jhony Jhons,jhon#gmail.com\n
You can try this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var regex = /,[0-9]+/g;
str.replace(regex, '\n');
The snippet above may output what you want, i.e. Jhony Jhons,jhon#gmail.com\n
There's a lot of ways to that, and this is so easy, so try this simple answer:-
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var splitted = str.split(","); //split them by comma
splitted.pop(); //removes the last element
var rec = splitted.join() + '\n'; //join them
You need a regex to select the complete phone number and also the preceding comma. Your current regex selects each digit and replaces each one with an "\n", resulting in a lot of "\n" in the result. Also the regex does not match the comma.
Use the following regex:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /,[0-9]+$/;
// it replaces all consecutive digits with the condition at least one digit exists (the "[0-9]+" part)
// placed at the end of the string (the "$" part)
// and also the digits must be preceded by a comma (the "," part in the beginning);
// also no need for global flag (/g) because of the $ symbol (the end of the string) which can be matched only once
var rec = str.trim().replace(regex, '\n'); //the result will be this string: Jhony Jhons,jhon#gmail.com\n
var str = "Jhony Jhons,jhon#gmail.com,380967574366";
var result = str.replace(/,\d+/g,'\\n');
console.log(result)

How I can replace a underscore with an space inside a word starting with an special char in javascript?

I have this string:
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}";
And I'm trying to replace the ALL the underscores with spaces for any word starting with exclamation sing (!) so the string should looks like this one:
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap Accessible},currentView:!map}";
I spent a few hours trying to figure out how to do that without success.
Try to use function replacement form (example):
str.replace(/!\w+/g, function(x) { return x.replace(/_/g, ' '); })
Regexp /!\w+/g selects all words started with "!". After that we replace each word x with result of x.replace(/_/g, ' ').
You can use the regex
!([^_]+)_([^]+)
and replace with $1 $2
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}";
console.log(str.replace(/!([^_]+)_([^]+)/g, "!$1 $2"));
(![^_]+)_([a-zA-Z0-9]+)
Try this.See demo.
http://regex101.com/r/tF5fT5/57
var re = /(![^_]+)_([a-zA-Z0-9]+)/gm;
var str = '{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}';
var subst = '$1 $2';
var result = str.replace(re, subst);

Categories

Resources