How to remove the extra spaces in a string? - javascript

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

Related

Recombine capture groups in single regexp?

I am trying to handle input groups similar to:
'...A.B.' and want to output '.....AB'.
Another example:
'.C..Z..B.' ==> '......CZB'
I have been working with the following:
'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1")
returns:
"....."
and
'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$2")
returns:
"AB"
but
'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1$2")
returns
"...A.B."
Is there a way to return
"....AB"
with a single regexp?
I have only been able to accomplish this with:
'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1") + '...A.B.'.replace(/(\.*)([A-Z]*)/g, "$2")
==> ".....AB"
If the goal is to move all of the . to the beginning and all of the A-Z to the end, then I believe the answer to
with a single regexp?
is "no."
Separately, I don't think there's a simpler, more efficient way than two replace calls — but not the two you've shown. Instead:
var str = "...A..B...C.";
var result = str.replace(/[A-Z]/g, "") + str.replace(/\./g, "");
console.log(result);
(I don't know what you want to do with non-., non-A-Z characters, so I've ignored them.)
If you really want to do it with a single call to replace (e.g., a single pass through the string matters), you can, but I'm fairly sure you'd have to use the function callback and state variables:
var str = "...A..B...C.";
var dots = "";
var nondots = "";
var result = str.replace(/\.|[A-Z]|$/g, function(m) {
if (!m) {
// Matched the end of input; return the
// strings we've been building up
return dots + nondots;
}
// Matched a dot or letter, add to relevant
// string and return nothing
if (m === ".") {
dots += m;
} else {
nondots += m;
}
return "";
});
console.log(result);
That is, of course, incredibly ugly. :-)

Invert brace from { to } and vise versa

I have a string with { and } how can I take all of them and reverse them, so all { become } and } become {?
I can't do this:
str = str.replace("}", "{");
str = str.replace("{", "}");
because that will make A face the same way as B then it will replace B which will all change them to the same direction.
I tried doing this:
str = str.replace(["{", "}"], ["}", "{"]);
But that just doesn't seem to do anything (not even error out).
So, what can I do to invert them?
You could use a regexp with a callback function to solve this:
str.replace(/\{|\}/g, function(match) {
return match == "}" ? "{" : "}";
});
You can use a temporary string that will definitely be unique to do the swap:
str = str.replace("}", "TEMP_HOLDER");
str = str.replace("{", "}");
str = str.replace("TEMP_HOLDER", "{");
But it's prone to a bug if the string contains the temp string and it also doesn't replace more than one occurrence. I'd suggest using Erik's answer.
You need to convert to something else in the first pass, and then convert to what you want after you've made the other conversions.
str = str.replace("{", "_###_");
str = str.replace("}", "{");
str = str.replace("_###_", "}");
Of course, the something else will need to be something that won't otherwise be in your string. You could use "\r\n" if you are sure you string won't contain newlines.
You could go with a two stage solution:
str = str.replace("}", "~");
str = str.replace("{", ",");
str = str.replace("~", "{");
str = str.replace(",", "}");

get detailed substring

i have a problem i'm trying to solve, i have a javascript string (yes this is the string i have)
<div class="stories-title" onclick="fun(4,'this is test'); navigate(1)
What i want to achieve are the following points:
1) cut characters from start until the first ' character (cut the ' too)
2) cut characters from second ' character until the end of the string
3) put what's remaining in a variable
For example, the result of this example would be the string "this is test"
I would be very grateful if anyone have a solution.. Especially a simple one so i can understand it.
Thanks all in advance
You can use split() function:
var mystr = str.split("'")[1];
var newstr = str.replace(/[^']+'([^']+).*/,'$1');
No need to cut anything, you just want to match the string between the first ' and the second ' - see similar questions like Javascript RegExp to find all occurences of a a quoted word in an array
var string = "<div class=\"stories-title\" onclick=\"fun(4,'this is test'); navigate(1)";
var m = string.match(/'(.+?)'/);
if (m)
return m[1]; // the matching group
You can use regular expressions
/\'(.+)\'/
http://rubular.com/r/RcVmejJOmU
http://www.regular-expressions.info/javascript.html
If you want to do the work yourself:
var str = "<div class=\"stories-title\" onclick=\"fun(4,'this is test'); navigate(1)";
var newstr = "";
for (var i = 0; i < str.length; i++) {
if (str[i] == '\'') {
while (str[++i] != '\'') {
newstr += str[i];
}
break;
}
}

Javascript Split String on First Space

I have the following code as part of a table sorting script. As it is now, it allows names in the "FIRST LAST" format to be sorted on LAST name by "reformatting" to "LAST, FIRST".
var FullName = fdTableSort.sortText;
function FullNamePrepareData(td, innerText) {
var a = td.getElementsByTagName('A')[0].innerHTML;
var s = innerText.split(' ');
var r = '';
for (var i = s.length; i > 0; i--) {
r += s[i - 1] + ', ';
}
return r;
}
It currently seems to sort on the name after the LAST space (ex. Jean-Claude Van Damme would sort on 'D').
How could I change this script to sort on the FIRST space (so Van Damme shows up in the V's)?
Thanks in advance!
Instead of the .split() and the loop you could do a replace:
return innerText.replace(/^([^\s]+)\s(.+)$/,"$2, $1");
That is, find all the characters up to the first space with ([^\s]+) and swap it with the characters after the first space (.+), inserting a comma at the same time.
You can shorten that functio a bit by the use of array methods:
function FullNamePrepareData(td, innerText) {
return innerText.split(' ').reverse().join(', ');
}
To put only the first name behind everything else, you might use
function FullNamePrepareData(td, innerText) {
var names = innerText.split(' '),
first = names.shift();
return names.join(' ')+', '+first;
}
or use a Regexp replace:
function FullNamePrepareData(td, innerText) {
return innerText.replace(/^(\S+)\s+([\S\s]+)/, "$2, $1");
}
I don't know where the sorting happens; it sounds like you just want to change the reordering output.
The simplest would be to use a regexp:
// a part without spaces, a space, and the rest
var regexp = /^([^ ]+) (.*)$/;
// swap and insert a comma
"Jean-Claude Van Damme".replace(regexp, "$2, $1"); // "Van Damme, Jean-Claude"
I think you're after this:
var words = innerText.split(' '),
firstName = words.shift(),
lastName = words.join(' ');
return lastName + ', ' + firstName;
Which would give you "Van Damme, Jean-Claude"

How to remove the end of a string, starting from a given pattern?

Let's say I have a string like this:
var str = "/abcd/efgh/ijkl/xxx-1/xxx-2";
How do I, using Javascript and/or jQuery, remove the part of str starting with xxx, till the end of str?
str.substring( 0, str.indexOf( "xxx" ) );
Just:
s.substring(0, s.indexOf("xxx"))
A safer version handling invalid input and lack of matching patterns would be:
function trump(str, pattern) {
var trumped = ""; // default return for invalid string and pattern
if (str && str.length) {
trumped = str;
if (pattern && pattern.length) {
var idx = str.indexOf(pattern);
if (idx != -1) {
trumped = str.substring(0, idx);
}
}
}
return (trumped);
}
which you'd call with:
var s = trump("/abcd/efgh/ijkl/xxx-1/xxx-2", "xxx");
Try using string.slice(start, end):
If you know the exact number of characters you want to remove, from your example:
var str = "/abcd/efgh/ijkl/xxx-1/xxx-2";
new_str = str.slice(0, -11);
This would result in str_new == '/abcd/efgh/ijkl/'
Why this is useful:
If the 'xxx' refers to any string (as the OP said), i.e: 'abc', '1k3', etc, and you do not know beforehand what they could be (i.e: Not constant), the accepted answers, as well as most of the others will not work.
Try this:
str.substring(0, str.indexOf("xxx"));
indexOf will find the position of xxx, and substring will cut out the piece you want.
This will take everything from the start of the string to the beginning of xxx.
str.substring(0,str.indexOf("xxx"));

Categories

Resources