$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.
I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s instead:
.replace(/\s/g,'')
You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
Now you can use "replaceAll":
console.log(' a b c d e f g '.replaceAll(' ',''));
will print:
abcdefg
But not working in every possible browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Regex for remove white space
\s+
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
or
[ ]+
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
Remove all white space at begin of string
^[ ]+
var str = " Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
remove all white space at end of string
[ ]+$
var str = "Visit Microsoft! ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
var mystring="fg gg";
console.log(mystring.replaceAll(' ',''))
** 100% working
use replace(/ +/g,'_'):
let text = "I love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')
console.log(text) // I_love_you
Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg
I don't understand why we need to use regex here when we can simply use replaceAll
let result = string.replaceAll(' ', '')
result will store string without spaces
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse
Use string.replace(/\s/g,'')
This will solve the problem.
Happy Coding !!!
simple solution could be : just replace white space ask key value
val = val.replace(' ', '')
Use replace(/\s+/g,''),
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
Well, we can also use that [^A-Za-z] with g flag for removing all the spaces in text. Where negated or complemente or ^. Show to the every character or range of character which is inside the brackets. And the about g is indicating that we search globally.
let str = "D S# D2m4a r k 23";
// We are only allowed the character in that range A-Za-z
str = str.replace(/[^A-Za-z]/g,""); // output:- DSDmark
console.log(str)
javascript - Remove ALL white spaces from text - Stack Overflow
Using .replace(/\s+/g,'') works fine;
Example:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
function RemoveAllSpaces(ToRemove)
{
let str = new String(ToRemove);
while(str.includes(" "))
{
str = str.replace(" ", "");
}
return str;
}
Related
For example
let myString = "This is my string";
let replacedString = myString.replace(/\ /g, "") //Thisismystring
Now that all the whitespaces have been removed, how do I put them back in the exact position?
Additionally, let's suppose the replaced string undergoes some change and becomes
let myChangedString = "(T)(h)(i)(s)(i)(s)(m)(y)(s)(t)(r)(i)(n)(g)";
Now I want to put the whitespaces back where they used to be i.e after (s) and before (i), after (s) and before (m), after (y) before (s)
I've spent a couple of hours on this and been stuck in the same position, any form of help would be greatly appreciated.
EDIT: Solved, thank you very much.
The trick here is to replace the spaces with another character - rather than just removing the space. That way - its a simple matter to replace the added character with a space to return the spaces to where they started. When I do this - I always use the tilde character "~" since it is easily recognisable as well as unlikely to actually be used in a string.
I have added a few variations / modifications as well as the example you have provided with every character being wrapped in parentheses - just note that you will need to escape these when replaceing the (~) for the " " space character.
let myString = "This is my string";
let replacedString = myString.replace(/\ /g, "~");
console.log(replacedString);//This~is~my~string
let modifiedString = replacedString.replace(/my/g, "your");
console.log(modifiedString);//This~is~your~string
let spacedString = modifiedString.replace(/~/g, " ");
console.log(spacedString);//This is your string
// using your example of wrapping each character in parentheses
let myChangedString = "(" + modifiedString.split('').join(")(") + ")";
console.log(myChangedString); //(T)(h)(i)(s)(~)(i)(s)(~)(y)(o)(u)(r)(~)(s)(t)(r)(i)(n)(g)
let mySpacedString = myChangedString.replace(/\(~\)/g, " ");
console.log(mySpacedString); //(T)(h)(i)(s) (i)(s) (y)(o)(u)(r) (s)(t)(r)(i)(n)(g)
Why not replace only the parts you need to be replaced?
For example search for word character and replace with the wanted parts.
console.log("This is my string".replace(/\w/g, '($&)'));
Better you just transform your original array. Loop through array and modify the char is not empty.
let myString = "This is my string";
let chars = [...myString].map(item => item !== ' ' ? '(' + item + ')': item)
console.log(chars.join(''))
Are you looking for this...
var result = "thisismystring".replace(/^(.{4})(.{2})(.{2})(.*)$/, "$1 $2 $3 $4");
alert(result);
The best way to explain this is by example. I'm using jQuery to do this.
Example I have a string
var str = "1.) Ben"
how can I dynamically omit the character 1.) including the space such that str === "Ben"
str can be dynamic such that order can increment from ones, tens, to hundreds.
E.G.
var str = "52.) Ken Bush"
or
var str = "182.) Hailey Quen"
Expected output
str === "Ken Bush"
or
str === "Hailey Quen"
Example
var str = "182.) Hailey Quen"
var test = str.split(') ');
test = test[1];
//output "Hailey Quen"
You can use regex replacement to get what you want.
var str = "182.) Hailey"
var newStr = str.replace(/^\d+\.\)\s*/, '')
// Hailey
var s = "1456.) Hard Spocker".replace(/^\d+\.\)\s*/, '')
// Hard Spocker
^ makes sure that the pattern is matched at the start of the string only
\d+ will match one or more digits.
\. will match the . with escaping
) is a symbol so we need to escape it using \ as \)
\s* will match one or more spaces.
You can learn about these symbols here.
Try using .substring() and .indexOf() as shown :-
var str = "182.) Hailey Quen"
alert(str.substring(str.indexOf(' ')))
DEMO
OR use .split() as shown :-
var str = "182.) Hailey Quen"
alert($.trim(str.split(')')[1]))
DEMO
You can do it regular expression,
var str = "52.) Ken".replace(/\d+\.\)\s/g,"");
console.log(str); //Ken
DEMO
If you have zero or more than zero spaces after the ) symbol then you can use *,
var str = "52.) Ken".replace(/\d+\.\)\s*/g,"");
console.log(str); //Ken
Dismantling regex used,
/ states regex left border
\d d states normal character d, if we want to make it match
numbers then we have to escape it with \
+ It states that one or more number should be there.
\. Again . is a metacharacter to match any valid character, so
escape it.
\) Parenthesis is also a metacharacter to close a group, escape
it.
\s* 12.) can be followed by zero or more spaces.
/ states regex right boundary.
g global flag, which used to do a search recursively.
You can do it like this
var testURL = "182.) Hailey Quen";
var output = testURL.substring(testURL.lastIndexOf(")") + 1).trim();
console.log(output);
*trim function will help to remove extra space if any.Hope it will help
I write this code for remove string from 'a' to 'c'
var str = "abcbbabbabcd";
var re = new RegExp("a.*?c","gi");
str = str.replace(re,"");
console.log(str);
The result in console is "bbd"
But the result that right for me is "bbabbd"
Can I use Regular Expression for this Problem ?
Thank for help.
a(?:(?!a).)*c
Use a lookahead based regex.See demo..*? will consume a as well after first a.To stop it use a lookahead.
https://regex101.com/r/cJ6zQ3/34
EDIT:
a[^a]*c
You can actually use negated character class as you have only 1 character.
The g means it's a global regexp, meaning it picks up both the abc and abbabc in the string. So this does properly remove the items from a..c. It seems you saw only two abc and missed the abbabc. The result bbd is actually correct as it does indeed "remove string from 'a' to 'c'".
abcbbabbabcd => bbd
Here is one more way.
var str = "abcbbabbabcd";
var str= str.replace(/abc/g, "");
console.log(str);
You need to update your regex to a[^ac]*?c , this will avoid character a and c between a and c
var str = "abcbbabbabcd";
var re = new RegExp("a[^ac]*?c","gi");
str = str.replace(re,"");
console.log(str);
I'm kind of a newby with Javascript, and regex in general and would appreciate all help I can receive!
Consider the following command: [Doesn't matter where it's executed]
/Ban Tom {Breaking The Rules} 5
What I need to do is detect the string between {}, replace the spaces with underscores there(_) and remove the curly brackets around the new string.
Example of outcome:
/Ban Tom Breaking_The_Rules 5
Thanks,
Tom.
You don't really need a RegEx as this can be achieved by just normal javascript:
<script type="text/javascript">
var str = "/Ban Tom {Breaking The Rules} 5";
var oldStr = str.substring(str.indexOf("{"), (str.indexOf("}") + 1));
var newStr = oldStr.replace(/ /g, "_").replace("{", "").replace("}", "");
alert(str.replace(oldStr, newStr));
</script>
use string.toCharArray() and parse through the array for matching { and spaces to replace them.
var str = '/Ban Tom {Breaking The Rules} 5';
var patt=new RegExp('{[^}].*}',i);
var res = patt.exec(str);
//include res check here.....
var newStr = res[0].replace(/ /g, '_');
newStr = newStr.replace(/[{}]/g, '');
str = newStr.replace(res[0], newStr);
// The Message:
var foo = "/Ban Tom {Breaking The Rules} 5";
// Replace Whitespace in braces:
foo = foo.replace(/\s+(?=[^\{\}]*\})/g, "_");
//Replace braces with nothing:
foo.replace(/[\{\}]/g,""):
First regex explanation:
\s+ // Match whitespace
(?= // If followed by:
[^\{\}]* // Any number of characters except braces
\} // The closing brace
) // End of the lookahed
This post provided most of the information, I just adapted it to javascript.
Is there an easy way to make this string:
(53.5595313, 10.009969899999987)
to this String
[53.5595313, 10.009969899999987]
with JavaScript or jQuery?
I tried with multiple replace which seems not so elegant to me
str = str.replace("(","[").replace(")","]")
Well, since you asked for regex:
var input = "(53.5595313, 10.009969899999987)";
var output = input.replace(/^\((.+)\)$/,"[$1]");
// OR to replace all parens, not just one at start and end:
var output = input.replace(/\(/g,"[").replace(/\)/g,"]");
...but that's kind of complicated. You could just use .slice():
var output = "[" + input.slice(1,-1) + "]";
For what it's worth, to replace both ( and ) use:
str = "(boob)";
str = str.replace(/[\(\)]/g, ""); // yields "boob"
regex character meanings:
[ = start a group of characters to look for
\( = escape the opening parenthesis
\) = escape the closing parenthesis
] = close the group
g = global (replace all that are found)
Edit
Actually, the two escape characters are redundant and eslint will warn you with:
Unnecessary escape character: ) no-useless-escape
The correct form is:
str.replace(/[()]/g, "")
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$1]")
This Javascript should do the job as well as the answer by 'nnnnnn' above
stringObject = stringObject.replace('(', '[').replace(')', ']')
If you need not only one bracket pair but several bracket replacements, you can use this regex:
var input = "(53.5, 10.009) more stuff then (12) then (abc, 234)";
var output = input.replace(/\((.+?)\)/g, "[$1]");
console.log(output);
[53.5, 10.009] more stuff then [12] then [abc, 234]