Remove and replace consecutive characters - javascript

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.

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 replace all newlines after reading a file

How can I replace a newline in a string with a ','? I have a string that is read from a file:
const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);
It takes a string from a file:
a,b,c,d,e,f
,,,,,
g,h,i,j,k,l
I'm able to detect the newline with this:
if (char === '\n')
But replacing \n like this doesn't work
str = csvString.replace('/\n/g');
I want to get the string to look like this:
a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,
You can add , at end of each line like this
$ - Matches end of line
let str = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`
let op = str.replace(/$/mg, "$&"+ ',')
console.log(op)
Try replacing the pattern $ with ,, comma:
var input = 'a,b,c,d,e,f';
input = input.replace(/$/mg, ",");
console.log(input);
Since you intend to retain the newlines/carriage returns, we can just take advantage of $ to represent the end of each line.
let text = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`;
let edited = text.replace(/\s+/g, '');
console.log( edited )
You can try this solution also. \s means white spaces.
You may try out like,
// Let us have some sentences havin linebreaks as \n.
let statements = " Programming is so cool. \n We love to code. \n We can built what we want. \n :)";
// We will console it and see that they are working fine.
console.log(statements);
// We may replace the string via various methods which are as follows,
// FIRST IS USING SPLIT AND JOIN
let statementsWithComma1 = statements.split("\n").join(",");
// RESULT
console.log("RESULT1 : ", statementsWithComma1);
// SECOND IS USING REGEX
let statementsWithComma2 = statements.replace(/\n/gi, ',');
// RESULT
console.log("RESULT2 : ", statementsWithComma2);
// THIRS IS USING FOR LOOP
let statementsWithComma3 = "";
for(let i=0; i < statements.length; i++){
if(statements[i] === "\n")
statementsWithComma3 += ','
else
statementsWithComma3 += statements[i]
}
// RESULT
console.log("RESULT3 : ", statementsWithComma3);
I believe in some systems newline is \r\n or just \r, so give /\r?\n|\r/ a shot

Remove multiple white space between text

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);

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

How to remove the extra spaces in a string?

What function will turn this contains spaces into this contains spaces using javascript?
I've tried the following, using similar SO questions, but could not get this to work.
var string = " this contains spaces ";
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,''); //"thiscontainsspaces"
Is there a simple pure javascript way to accomplish this?
You're close.
Remember that replace replaces the found text with the second argument. So:
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!
newString = string.replace(/\s+/g,' ').trim();
string.replace(/\s+/g, ' ').trim()
Try this one, this will replace 2 or 2+ white spaces from string.
const string = " this contains spaces ";
string.replace(/\s{2,}/g, ' ').trim()
Output
this contains spaces
I figured out one way, but am curious if there is a better way...
string.replace(/\s+/g,' ').trim()
I got the same problem and I fixed like this
Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
I think images always explain it's good, basically what you see that the regex \s meaning in regex is whitespace. the + says it's can be multiply times. /g symbol that it's looks globally (replace by default looks for the first occur without the /g added). and the trim will remove the last and first whitespaces if exists.
Finally, To remove extra whitespaces you will need this code:
newString = string.replace(/\s+/g,' ').trim();
We can use the below approach to remove extra space in a sentence/word.
sentence.split(' ').filter(word => word).join(' ')
Raw Javascript Solution:
var str = ' k g alok deshwal';
function removeMoreThanOneSpace() {
String.prototype.removeSpaceByLength=function(index, length) {
console.log("in remove", this.substr(0, index));
return this.substr(0, index) + this.substr(length);
}
for(let i = 0; i < str.length-1; i++) {
if(str[i] === " " && str[i+1] === " ") {
str = str.removeSpaceByLength(i, i+1);
i = i-1;
}
}
return str;
}
console.log(removeMoreThanOneSpace(str));
var s=" i am a student "
var r='';
console.log(s);
var i,j;
j=0;
for(k=0; s[k]!=undefined; k++);// to calculate the length of a string
for(i=0;i<k;i++){
if(s[i]!==' '){
for(;s[i]!==' ';i++){
r+=s[i];
}
r+=' ';
}
}
console.log(r);
// Here my solution
const trimString = value => {
const allStringElementsToArray = value.split('');
// transform "abcd efgh" to ['a', 'b', 'c', 'd',' ','e', 'f','g','h']
const allElementsSanitized = allStringElementsToArray.map(e => e.trim());
// Remove all blank spaces from array
const finalValue = allElementsSanitized.join('');
// Transform the sanitized array ['a','b','c','d','e','f','g','h'] to 'abcdefgh'
return finalValue;
}
I have tried regex to solve this problem :
let temp=text.replace(/\s{2,}/g, ' ').trim()
console.log(temp);
input="Plese complete your work on Time"
output="Please complete your work on Time"
//This code remove extra spaces with out using "string objectives"
s=" This Is Working On Functions "
console.log(s)
final="";
res='';
function result(s) {
for(var i=0;i<s.length;i++)
{
if(!(final==""&&s[i]==" ")&&!(s[i]===" "&& s[i+1] ===" ")){
final+=s[i];
}
}
console.log(final);
}
result(s);

Categories

Resources