How to replace all the \ from a string with space in javascript? - javascript

For example:
var str="abc\'defgh\'123";
I want to remove all the \ using Javascript. I have tried with several functions but still can't replace all the forward slashes.

I've posted a huuuge load of bollocks on JS and multiple replace functionality here. But in your case any of the following ways will do nicely:
str = str.replace('\\',' ');//Only replaces first occurrence
str = str.replace(/\\/g,' ');
str = str.split('\\').join(' ');
As #Guillaume Poussel pointed out, the first approach only replaces one occurrence of the backslash. Don't use that one, either use the regex, or (if your string is quite long) use the split().join() approach.

Just use the replace function like this:
str = str.replace('\\', ' ');
Careful, you need to escape \ with another \. The function returns the modified string, it doesn't modify the string on which it is called, so you need to catch the return value like in my example! So just doing:
str.replace('\\', ' ');
And then using str, will work with the original string, without the replacements.

str="abc\\'asdf\\asdf"
str=str.replace(/\\/g,' ')
You want to replace all '\' in your case, however, the function replace will only do replacing once if you use '\' directly. You have to write the pattern as a regular expression.
See http://www.w3schools.com/jsref/jsref_replace.asp.

Try:
string.replace(searchvalue,newvalue)
In your case:
str.replace('\\', ' ');

Using string.replace:
var result = str.replace('\\', ' ');
Result:
"abc 'defgh '123"

Related

Javascript (Regex): How do i replace (Backslash + Double Quote) pairs?

In Javascript, i want the below original string:
I want to replace \"this\" and \"that\" words, but NOT the one "here"
.. to become like:
I want to replace ^this^ and ^that^ words, but NOT the one "here"
I tried something like:
var str = 'I want to replace \"this\" and \"that\" words, but NOT the one "here"';
str = str.replace(/\"/g,"^");
console.log( str );
Demo: JSFiddle here.
But still .. the output is:
I want to replace ^this^ and ^that^ words, but NOT the one ^here^
Which means i wanted to replace only the \" occurrences but NOT the " alone. But i cannot.
Please help.
As #adeneo's comment, your string was created wrong and not exactly like your expectation. Please try this:
var str = 'I want to replace \\"this\\" and \\"that\\" words, but not the one "here"';
str = str.replace(/\\\"/g,"^");
console.log(str);
You can use RegExp /(")/, String.prototype.lastIndexOf(), String.prototype.slice() to check if matched character is last or second to last match in input string. If true, return original match, else replace match with "^" character.
var str = `I want to replace \"this\" and \"that\" words, but NOT the one "here"`;
var res = str.replace(/(")/g, function(match, _, index) {
return index === str.lastIndexOf(match)
|| index === str.slice(0, str.lastIndexOf(match) -1)
.lastIndexOf(match)
? match
: "^"
});
console.log(res);
The problem with String.prototype.replace is that it only replaces the first occurrence without Regular Expression. To fix this, you need to add a g and the end of the RegEx, like so:
var mod = str => str.replace(/\\\"/g,'^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');
A less effective but easier to understand to do what you wanted is to split the string with the delimiter and then join it with the replacement, like so:
var mod = str => str.split('\\"').join('^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');
Note: You can wrap a string with either ' or ". Suppose your string contains ", i.e. a"a, you will need to put an \ in front of the " as "a"a" causes syntax error. 'a"a' won't cause syntax error as the parser knows the " is part of the string, but when you put a \ in front of " or any other special characters, it means the following character is a special character. So 'a\"a' === 'a"a' === "a\"a". If you want to store \, you will need to use \ regardless of the type of quote you use, so to store \", you will need to use '\\"', '\\\"' or "\\\"".

Regular expression for removing whitespaces

I have some text which looks like this -
" tushar is a good boy "
Using javascript I want to remove all the extra white spaces in a string.
The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this -
"tushar is a good boy"
I am using the following code at the moment-
str.replace(/(\s\s\s*)/g, ' ')
This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.
This can be done in a single String#replace call:
var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// gives: "tushar is a good boy"
This works nicely:
function normalizeWS(s) {
s = s.match(/\S+/g);
return s ? s.join(' ') : '';
}
trims leading whitespace
trims trailing whitespace
normalizes tabs, newlines, and multiple spaces to a single regular space
Try this:
str.replace(/\s+/g, ' ').trim()
If you don't have trim add this.
Trim string in JavaScript?
Since everyone is complaining about .trim(), you can use the following:
str.replace(/\s+/g,' ' ).replace(/^\s/,'').replace(/\s$/,'');
JSFiddle
This regex may be useful to remove the whitespaces
/^\s+|\s+$/g
Try:
str.replace(/^\s+|\s+$/, '')
.replace(/\s+/, ' ');
try
var str = " tushar is a good boy ";
str = str.replace(/^\s+|\s+$/g,'').replace(/(\s\s\s*)/g, ' ');
first replace is delete leading and trailing spaces of a string.

javascript - replace dash (hyphen) with a space

I have been looking for this for a while, and while I have found many responses for changing a space into a dash (hyphen), I haven't found any that go the other direction.
Initially I have:
var str = "This-is-a-news-item-";
I try to replace it with:
str.replace("-", ' ');
And simply display the result:
alert(str);
Right now, it doesn't do anything, so I'm not sure where to turn. I tried reversing some of the existing ones that replace the space with the dash, and that doesn't work either.
Thanks for the help.
This fixes it:
let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);
There were two problems with your code:
First, String.replace() doesn’t change the string itself, it returns a changed string.
Second, if you pass a string to the replace function, it will only replace the first instance it encounters. That’s why I passed a regular expression with the g flag, for 'global', so that all instances will be replaced.
replace() returns an new string, and the original string is not modified. You need to do
str = str.replace(/-/g, ' ');
I think the problem you are facing is almost this: -
str = str.replace("-", ' ');
You need to re-assign the result of the replacement to str, to see the reflected change.
From MSDN Javascript reference: -
The result of the replace method is a copy of stringObj after the
specified replacements have been made.
To replace all the -, you would need to use /g modifier with a regex parameter: -
str = str.replace(/-/g, ' ');
var str = "This-is-a-news-item-";
while (str.contains("-")) {
str = str.replace("-", ' ');
}
alert(str);
I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.
http://jsfiddle.net/LGCYF/
In addition to the answers already given you probably want to replace all the occurrences. To do this you will need a regular expression as follows :
str = str.replace(/-/g, ' '); // Replace all '-' with ' '
Use replaceAll() in combo with trim() may meet your needs.
const str = '-This-is-a-news-item-';
console.log(str.replaceAll('-', ' ').trim());
Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.
var str = "This-is---a--news-----item----";
Then to replace all dashes with single spaces, you could do this:
var newStr = str.split('-').filter(function(item) {
item = item ? item.replace(/-/g, ''): item
return item;
}).join(' ');
Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:
item = item ? item.replace(/-/g, ''): item
The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.
Then when your string join runs on the filtered elements, you end up with this output:
"This is a news item"
Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.
if its array like
arr = ["This-is-one","This-is-two","This-is-three"];
arr.forEach((sing,index) => {
arr[index] = sing.split("-").join(" ")
});
Output will be
['This is one', 'This is two', 'This is three']

How to replace underscores with spaces using a regex in Javascript

How can I replace underscores with spaces using a regex in Javascript?
var ZZZ = "This_is_my_name";
If it is a JavaScript code, write this, to have transformed string in ZZZ2:
var ZZZ = "This_is_my_name";
var ZZZ2 = ZZZ.replace(/_/g, " ");
also, you can do it in less efficient, but more funky, way, without using regex:
var ZZZ = "This_is_my_name";
var ZZZ2 = ZZZ.split("_").join(" ");
Regular expressions are not a tool to replace texts inside strings but just something that can search for patterns inside strings. You need to provide a context of a programming language to have your solution.
I can tell you that the regex _ will match the underscore but nothing more.
For example in Groovy you would do something like:
"This_is_my_name".replaceAll(/_/," ")
===> This is my name
but this is just language specific (replaceAll method)..
var str1="my__st_ri_ng";
var str2=str1.replace(/_/g, ' ');
Replace "_" with " "
The actual implementation depends on your language.
In Perl it would be:
s/_/ /g
But the truth is, if you are replacing a fixed string with something else, you don't need a regular expression, you can use your language/library's basic string replacement algorithms.
Another possible Perl solution would be:
tr/_/ /
To replace the underscores with spaces in a string, call the replaceAll() method, passing it an underscore and space as parameters, e.g. str.replaceAll('_', ' '). The replaceAll method will return a new string where each underscore is replaced by a space.
const str = 'apple_pear_melon';
// ✅ without regular expression
const result1 = str.replaceAll('_', ' ');
console.log(result1); // 👉️ "apple pear melon"
// ✅ with regular expression
const result2 = str.replace(/_+/g, ' ');
console.log(result2); // 👉️ "apple pear melon"

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...
I have this:
var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');
locationArray = locationClean.split(" ");
console.log(location);
console.log(locationClean);
console.log(locationArray);
And here is what I am getting in Firebug:
stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]
So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).
Thanks all.
Use a pattern instead of a string, which you can use with the "global" modifier
locationClean = location.replace(/\//g,' ');
The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:
locationClean = location.replace(/\//g,' ');
(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)
Still, why are you not just splitting on the '/' character instead?
You could directly split using the / character as the separator:
var loc = location.host + location.pathname, // loc variable used for tesing
locationArray = loc.split("/");
This can be fixed from your javascript.
SYNTAX
stringObject.replace(findstring,newstring)
findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.
newstring: Required. Specifies the string to replace the found value from findstring
Here's what ur code shud look like:
locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");
njoi'

Categories

Resources