How to replace all the zeros in javascript - javascript

How can I replace all the zeroes with asterisks in a string?
I've tried:
var a = "00000004567";
a.replace(/0*\d/g,'*');
The problem is that it returns: "****567", which is undesirable.

var a = '00000004567';
a.replace(/0/g, '*');

Remove the *\d to convert all the zeroes to asterisks. The g modifier will handle the rest.
var a = "00000004567";
console.log(a.replace(/0/g, '*'))

Assuming you're talking about a string, use the global modifier like this:
a.replace(/0/g,"*");

Related

Replace occurance in a string with the result

I have the following string:
{"key1":"value1","key2":"value2","key3":"value3"}
I want to convert it into this:
{key1:"value1",key2:"value2",key3:"value3"}
So I did something like this:
var output = str.replace(/"(.*?)":/, "$1:");
This way I get:
{key1:"value1","key2":"value2","key3":"value3"}
So it works for the first key, but not for the rest. How can I use the replace method to replace all occurrences like I showed here?
Use a global flag with your regex
str.replace(/"(.*?)":/g, "$1:");
You need to change the regex:
var output = str.replace(/"(.*?)":/g, "$1:");

How to replace all \" in a JS string?

How to replace all \" to " in a string?
I tried, but it doesn't works: var foobar = ("foo\\\"bar\\\"foo").replace(/"\\\""/,'"');
The result is foo\"bar\"foo , but it should be foo"bar"foo
You don't need to use quotes inside of a RegEx pattern, the // delimiters act as ones.
var foobar = "foo\\\"bar\\\"foo".replace(/\\"/g,'"');
Works for me.
Try .replace(/\\"/g,'"'); - regexes don't need quotes around them, I'm surprised you get any result at all.
You need to fix your regex, you need to do
replace(/\\\"/g, "\"")
Your quoting is wrong and you're not using g - global flag. It should be:
var foobar = ("foo\\\"bar\\\"foo").replace(/\\"/g,'"');
Try defining it like this
var foobar = ("foo\\\"bar\\\"foo").replace(/"\\\""/g,'"');
note that the .replace has a /g which makes it global
jsfiddle
// initial string
var str = "AAAbbbAAAccc";
// replace here
str = str.replace(/A/g, "Z");
alert(str);
​

Simple Javascript string manipulation

I have a string that will look something like this:
I'm sorry the code "codehere" is not valid
I need to get the value inside the quotes inside the string. So essentially I need to get the codehere and store it in a variable.
After some researching it looks like I could loop through the string and use .charAt(i) to find the quotes and then pull the string out one character at a time in between the quotes.
However I feel there has to be a simpler solution for this out there. Any input would be appreciated. Thanks!
You could use indexOf and lastIndexOf to get the position of the quotes:
var openQuote = myString.indexOf('"'),
closeQuote = myString.lastIndexOf('"');
Then you can validate they are not the same position, and use substring to retrieve the code:
var code = myString.substring(openQuote, closeQuote + 1);
Regex:
var a = "I'm sorry the code \"codehere\" is not valid";
var m = a.match(/"[^"]*"/ig);
alert(m[0]);
Try this:
var str = "I'm sorry the code \"cod\"eh\"ere\" is not valid";
alert(str.replace(/^[^"]*"(.*)".*$/g, "$1"));
You could use Javascript's match function. It takes as parameter, a regular expression. Eg:
/\".*\"/
Use regular expressions! You can find a match using a simple regular expressions like /"(.+)"/ with the Javascript RegExp() object. Fore more info see w3schools.com.
Try this:
var msg = "I'm sorry the code \"codehere\" is not valid";
var matchedContent = msg.match(/\".*\"/ig);
//matchedContent is an array
alert(matchedContent[0]);
You should use a Regular Expression. This is a text pattern matcher that is built into the javascript language. Regular expressions look like this: /thing to match/flags* for example, /"(.*)"/, which matches everything between a set of quotes.
Beware, regular expressions are limited -- they can't match nested things, so if the value inside quotes contains quotes itself, you'll end up with a big ugly mess.
*: or new RegExp(...), but use the literal syntax; it's better.
You could always use the .split() string function:
var mystring = 'I\'m sorry the code "codehere" is not valid' ;
var tokens = [] ;
var strsplit = mystring.split('\"') ;
for(var i=0;i<strsplit.length;i++) {
if((i % 2)==0) continue; // Ignore strings outside the quotes
tokens.push(strsplit[i]) ; // Store strings inside quotes.
}
// Output:
// tokens[0] = 'codehere' ;

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'

Strip all non-numeric characters from string in JavaScript

Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9 should be kept.
var myString = 'abc123.8<blah>';
//desired output is 1238
How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.
Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');
If you need this to leave the dot for float numbers, use this
var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"
Use a regular expression, if your script implementation supports them. Something like:
myString.replace(/[^0-9]/g, '');
You can use a RegExp to replace all the non-digit characters:
var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238
Something along the lines of:
yourString = yourString.replace ( /[^0-9]/g, '' );
Short function to remove all non-numeric characters but keep the decimal (and return the number):
parseNum = str => +str.replace(/[^.\d]/g, '');
let str = 'a1b2c.d3e';
console.log(parseNum(str));
In Angular / Ionic / VueJS -- I just came up with a simple method of:
stripNaN(txt: any) {
return txt.toString().replace(/[^a-zA-Z0-9]/g, "");
}
Usage on the view:
<a [href]="'tel:'+stripNaN(single.meta['phone'])" [innerHTML]="stripNaN(single.meta['phone'])"></a>
The problem with these answers above, is that it assumes whole numbers. But if you need a floating point value, then the previous reg string will remove the decimal point.
To correct this you need write a negated character class with ^
var mystring = mystring.replace(/[^0-9.]/g, '');
try
myString.match(/\d/g).join``
var myString = 'abc123.8<blah>'
console.log( myString.match(/\d/g).join`` );
Unfortunately none of the answers above worked for me.
I was looking to convert currency numbers from strings like $123,232,122.11 (1232332122.11) or USD 123,122.892 (123122.892) or any currency like ₹ 98,79,112.50 (9879112.5) to give me a number output including the decimal pointer.
Had to make my own regex which looks something like this:
str = str.match(/\d|\./g).join('');
This,
.match(/\d|\.|\-/g).join('');
Handles both , and . also -
Example:
"Balance -$100,00.50".match(/\d|\.|\-/g).join('');
Outputs
10000.50
we are in 2017 now you can also use ES2016
var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));
or
console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));
The result is
1238

Categories

Resources