There is a problem.
After JSON.stringify I have a string:
value.value_new = {"apiunits":{"amount":"0"},"total":{"requests":"10","results":"10"},"project":{"projects":"1"}};
I want to replace { and }, and I try to do it this way:
value.value_new = value.value_new.replace("/[{}]/g", " ");
or
value.value_new = value.value_new.replace("/{/g", " ");
value.value_new = value.value_new.replace("/}/g", " ");
But it doesn't work. Why?
value.value_new is not a string, so you can't use the function replace on it.
If you just need this string without the brackets, you can use this method :
var value = {};
value.value_new = '{"apiunits":{"amount":"0"},"total":{"requests":"10","results":"10"},"project":{"projects":"1"}}';
String.prototype.replaceAll = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}
value.value_new = value.value_new.replaceAll("{", '');
value.value_new = value.value_new.replaceAll("}", '');
console.log(value.value_new); // You'll have the string that you want
I'm not sure why you would want to do that or what you would do with the result, but I think the RegEx you want is:
var asString = '{"apiunits":{"amount":"0"},"total":{"requests":"10","results":"10"},"project":{"projects":"1"}};'
//Replace either curly with a space. Note in RegEx you have to escape the curly braces with a backslash
var replaced = asString.replace(/\{|\}/gi, ' ');
console.log(replaced);
//outputs -->" "apiunits": "amount":"0" ,"total": "requests":"10","results":"10" ,"project": "projects":"1" ;"
In my example, I'm using the pipe for "or" but either of your previous attempts would work if the curly braces were escaped:
value = value.replace("/[\{\}]/g", " ");
or
value = value.replace("/\{/g", " ");
value = value.replace("/\}/g", " ");
Related
I have a string - "hi#i#am#hum'#'an ";
I want to split the string for an operator #, but don't want to split the string which is under single quote.
So I want the result - ["hi","i","am","hum#an"]
Try
input.split( /#(?!')/ )
Demo
var output = "hi#i#am#hum'#'an ".split( /#(?!')/ ).map( s => s.replace(/'#'/g, "#") );
console.log( output );
Here is another solution, not a one liner though. First replace '#' with some temporary character. Then apply the split, and replace temp character with #.
var str = "hi#i#am#hum'#'an";
str = str.replace(/'#'/g, '&');
str = str.split('#');
str = str.map(s => s.replace(/&/g, '#'))
console.log(str);
function space(str,numSpace){
str = "";
numSpace = (" " + " ");
document.write(numSpace + str + numSpace);
}
console.log(space("hi", " "));
This is not working out, I'm not too sure how I can add whitespace to both ends of a string.
This is not working out, i'm not too sure how I can add whitespace to
both ends of a string.
you're always resetting the parameter str to empty string hence the unexpected behaviour.
there are two ways you could solve the issue at hand.
1) you could use console.log() inside the method, example:
function space(str, numSpace) {
var result = numSpace + str + numSpace;
console.log(result);
}
space("hi", " ");
2) you could return the value then use console.log():
function space(str, numSpace) {
return numSpace + str + numSpace;
}
var result = space("hi", " ");
console.log(result);
Don't overwrite you're function's parameters with constants, and don't use document.write but return the result:
function space(str, numSpace) {
return numSpace + str + numSpace;
}
console.log(space("hi", " "));
Also I would suggest renaming numSpace to spaces, as the former suggests to be used with an integer count, not a string of spaces.
Like the title says, i would like to remove an underscore within a String with a regex. This is what i have:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-zA-Z]/g, '',/\s/g, '',/[0-9]/g,'');
if (str.split("").reverse().join("") !== str) {
return false;
}
else {
return true;
}
}
palindrome("eye");
Use .replace(/_/g, "") to remove all underscores or use .replace(/_/g, " ") to replace them with a space.
Here is an example to remove them:
var str = "Yeah_so_many_underscores here";
var newStr = str.replace(/_/g, "");
alert(newStr);
You can use .replace to achieve this. Use the following code. It will replace all _ with the second parameter. In our case we don't need a second parameter so all _ will be removed.
<script>
var str = "some_sample_text_here.";
var newStr = str.replace(/_/g , "");
alert ('Text without underscores : ' + newStr);
</script>
str.replace(/_/g, '');
This should work.
you can remove underscore from response or any string
like this: "hello_rizo"
Code:
var rizo="hello_rizo"
console.log('output', e.response.data.message.replace(/(^|_)./g, s => s.slice(-1).toUpperCase()));
output:
hellorizo
I want to remove the white space which is there in the start of the string
It should remove only the space at the start of the string, other spaces should be there.
var string=' This is test';
This is what you want:
function ltrim(str) {
if(!str) return str;
return str.replace(/^\s+/g, '');
}
Also for ordinary trim in IE8+:
function trimStr(str) {
if(!str) return str;
return str.replace(/^\s+|\s+$/g, '');
}
And for trimming the right side:
function rtrim(str) {
if(!str) return str;
return str.replace(/\s+$/g, '');
}
Or as polyfill:
// for IE8
if (!String.prototype.trim)
{
String.prototype.trim = function ()
{
// return this.replace(/^\s+|\s+$/g, '');
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
if (!String.prototype.trimStart)
{
String.prototype.trimStart = function ()
{
// return this.replace(/^\s+/g, '');
return this.replace(/^[\s\uFEFF\xA0]+/g, '');
};
}
if (!String.prototype.trimEnd)
{
String.prototype.trimEnd = function ()
{
// return this.replace(/\s+$/g, '');
return this.replace(/[\s\uFEFF\xA0]+$/g, '');
};
}
Note:
\s: includes spaces, tabs \t, newlines \n and few other rare characters, such as \v, \f and \r.
\uFEFF: Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
\xA0: ASCII 0xA0 (160: non-breaking space) is not recognised as a space character
Try to use javascript's trim() function, Basically it will remove the leading and trailing spaces from a string.
var string=' This is test';
string = string.trim();
DEMO
So as per the conversation happened in the comment area, in order to attain the backward browser compatibility just use jquery's $.trim(str)
var string=' This is test';
string = $.trim(string)
You can use String.prototype.trimStart(). Like this:
myString=myString.trimStart();
An if you want to trim the tail, you can use:
myString=myString.trimEnd();
Notice, this 2 functions are not supported on IE. For IE you need to use polyfills for them.
You should use javascript trim function
var str = " Hello World! ";
alert(str.trim());
This function can also remove white spaces from the end of the string.
Easiest solution: (ES10 feature trimStart())
var string= 'This is a test';
console.log(string.trimStart());
.trimLeft() can be used for this.
const str = " string ";
console.log(str.trimLeft()); // => "string "
Just a different and a not so efficient way to do it
var str = " My string";
function trim() {
var stringStarted = false;
var newString = "";
for (var i in str) {
if (!stringStarted && str[i] == " ") {
continue;
}
else if (!stringStarted) {
stringStarted = true;
}
newString += str[i];
}
return newString;
}
console.log(trim(str));
I am really sure this doesn't work for anything else and is not the most optimum solution, but this just popped into my mind
You want to remove the space (i.e whitespace) at the beginning of the string. So, could not use standard jquesy .trim(). You can use the regex to find and replace the whitespace at the beginning of the string.
Try this:
.replace(/^\s+/g, "")
Read this post
Try this:
var string=' This is test ';
alert(string.replace(/^\s+/g, ""));
Working Example
OR if you want to remove the whitespace from the beginning and end then use .trim()
var string=' This is test';
$.trim(string);
There is JQuery.trim() function but it is trimming the white spaces.
But I want to do it like in C#.
string props = ",width=400,height=400,status=0,location=0,";
props.Trim(',');
// result will be: "width=400,height=400,status=0,location=0"
How can I do this? Actually I would like to use it for general input param not only for ','..
Try an regexp:
var props=",width=400,height=400,status=0,location=0,";
props=props.replace(/^[,]*(.*?)[,]*$/, "$1");
If you, for example, also want to remove semicolons at the beginning or the end, use this:
props=props.replace(/^[,;]*(.*?)[,;]*$/, "$1");
And if you want to remove spaces, too, but only at the end:
props=props.replace(/^[,;]*(.*?)[,; ]*$/, "$1");
I found a link do this with functions and I found another link how to add this function to the String type. And I wrote below code and its test link :
String.prototype.TrimLeft = function (chars) {
//debugger;
var re = chars ? new RegExp("^[" + chars + "]+/", "g")
: new RegExp(/^\s+/);
return this.replace(re, "");
}
String.prototype.TrimRight = function (chars) {
var re = chars ? new RegExp("[" + chars + "]+$/", "g")
: new RegExp(/\s+$/);
return this.replace(re, "");
}
String.prototype.Trim = function (chars) {
return this.TrimLeft(chars).TrimRight(chars);
}
^[" + chars + "]+ is finding the characters at the begining of string.
And it is replacing on this line: this.replace(re, "");
With this : [" + chars + "]+$, it is searching characters at the end of string g(globally) and replacing with the same method.
var c=",width=400,height=400,status=0,";
c.Trim(",");
// result: width=400,height=400,status=0