Is there a way to replace every "%20" with a space using JavaScript. I know how to replace a single "%20" with a space but how do I replace all of them?
var str = "Passwords%20do%20not%20match";
var replaced = str.replace("%20", " "); // "Passwords do%20not%20match"
Check this out:
How to replace all occurrences of a string in JavaScript?
Short answer:
str.replace(/%20/g, " ");
EDIT:
In this case you could also do the following:
decodeURI(str)
The percentage % sign followed by two hexadecimal numbers (UTF-8 character representation) typically denotes a string which has been encoded to be part of a URI. This ensures that characters that would otherwise have special meaning don't interfere. In your case %20 is immediately recognisable as a whitespace character - while not really having any meaning in a URI it is encoded in order to avoid breaking the string into multiple "parts".
Don't get me wrong, regex is the bomb! However any web technology worth caring about will already have tools available in it's library to handle standards like this for you. Why re-invent the wheel...?
var str = 'xPasswords%20do%20not%20match';
console.log( decodeURI(str) ); // "xPasswords do not match"
Javascript has both decodeURI and decodeURIComponent which differ slightly in respect to their encodeURI and encodeURIComponent counterparts - you should familiarise yourself with the documentation.
Use the global flag in regexp:
var replaced = str.replace(/%20/g, " ");
^
using unescape(stringValue)
var str = "Passwords%20do%20not%20match%21";
document.write(unescape(str))
//Output
Passwords do not match!
use decodeURI(stringValue)
var str = "Passwords%20do%20not%20match%21";
document.write(decodeURI(str))
Space = %20
? = %3F
! = %21
# = %23
...etc
This method uses the decodeURIComponent() (See edit below) method, which is the best one.
var str = "Passwords%20do%20not%20match%21";
alert(decodeURIComponent(str))
Here it how it works:
Space = %20
? = %3F
! = %21
# = %23
...etc
There's a good example of that at the Mozilla docs [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI]
Edit: decodeURIComponent works better, look at the example.
If you want to use jQuery you can use .replaceAll()
If you need to remove white spaces at the end then here is a solution:
https://www.geeksforgeeks.org/urlify-given-string-replace-spaces/
const stringQ1 = (string)=>{
//remove white space at the end
const arrString = string.split("")
for(let i = arrString.length -1 ; i>=0 ; i--){
let char = arrString[i];
if(char.indexOf(" ") >=0){
arrString.splice(i,1)
}else{
break;
}
}
let start =0;
let end = arrString.length -1;
//add %20
while(start < end){
if(arrString[start].indexOf(' ') >=0){
arrString[start] ="%20"
}
start++;
}
return arrString.join('');
}
console.log(stringQ1("Mr John Smith "))
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);
I want to select the last .csv in text.csv.csv
I tried (\.csv)$ but it didn't work.
I am using this site to test my regax
https://regex101.com/#javascript
Please try:
/\.csv$/
Added '\' to escape the dot.
You need to use a backslash to escape the dot character, to check if the dot is present.
If you don't escape it, the dot represents a single character, so, for example, 'test.csv.xxxcsv' would match too.
Working example
Why do you need regex for this?
Simple JavaScript functions should suffice
var str = "myFileName.csv";
var index = str.lastIndexOf(".csv");
var len = str.length;
var res = "";
if(len - index == 4)
{
res = "CSV Found"
}
else {
res = "CSV Not Found"
};
I have a string and want to add a colon after every 2nd character (but not after the last set), eg:
12345678
becomes
12:34:56:78
I've been using .replace(), eg:
mystring = mystring.replace(/(.{2})/g, NOT SURE WHAT GOES HERE)
but none of the regex for : I've used work and I havent been able to find anything useful on Google.
Can anyone point me in the right direction?
Without the need to remove any trailing colons:
mystring = mystring.replace(/..\B/g, '$&:')
\B matches a zero-width non-word boundary; in other words, when it hits the end of the string, it won't match (as that is considered to be a word boundary) and therefore won't perform the replacement (hence no trailing colon, either).
$& contains the matched substring (so you don't need to use a capture group).
mystring = mystring.replace(/(..)/g, '$1:').slice(0,-1)
This is what comes to mind immediately. I just strip off the final character to get rid of the colon at the end.
If you want to use this for odd length strings as well, you just need to make the second character optional. Like so:
mystring = mystring.replace(/(..?)/g, '$1:').slice(0,-1)
If you're looking for approach other than RegEx, try this:
var str = '12345678';
var output = '';
for(var i = 0; i < str.length; i++) {
output += str.charAt(i);
if(i % 2 == 1 && i > 0) {
output += ':';
}
}
alert(output.substring(0, output.length - 1));
Working JSFiddle
A somewhat different approach without regex could be using Array.prototype.reduce:
Array.prototype.reduce.call('12345678', function(acc, item, index){
return acc += index && index % 2 === 0 ? ':' + item : item;
}, ''); //12:34:56:78
mystring = mytring.replace(/(.{2})/g, '\:$1').slice(1)
try this
Easy, just match every group of up-to 2 characters and join the array with ':'
mystring.match(/.{1,2}/g).join(':')
var mystring = '12345678';
document.write(mystring.match(/.{1,2}/g).join(':'))
no string slicing / trimming required.
It's easier if you tweak what you're searching for to avoid an end-of-line colon(using negative lookahead regex)
mystring = mystring.replace(/(.{2})(?!$)/g, '\$1:');
mystring = mystring.replace(/(.{2})/g, '$1\:')
Give that a try
I like my approach the best :)
function colonizer(strIn){
var rebuiltString = '';
strIn.split('').forEach(function(ltr, i){
(i % 2) ? rebuiltString += ltr + ':' : rebuiltString += ltr;
});
return rebuiltString;
}
alert(colonizer('Nicholas Abrams'));
Here is a demo
http://codepen.io/anon/pen/BjjNJj
$("#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;
}
Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);