Javascript replace regex using [duplicate] - javascript

This question already has answers here:
Removing Numbers from a String using Javascript
(2 answers)
Closed 3 years ago.
I need to change #x ( x a number) to x.
How can I do that, I don't know js regex..

You can try like this.
var n = Number(s.replace(/\D+/, ''))
> var s = "#123";
undefined
>
> var n = s.replace(/\D+/, '')
undefined
>
> n
'123'
>
> n = Number(n)
123
>
> n + 7
130
>

Just use replace like so:
const str = "#1235";
const num = str.replace("#", "");
console.log(num);

You can use inbuilt replace function for this purpose, which can take both, literals and regex pattern as parameter.
var str = "#12345";
str.replace("#", "");
We can also use patterns in the replace parameter, if you have multiple values to be replaced.
var str = "#123#45";
str.replace(/[##]/,"") // prints "123#45" => removes firs occurrence only
str.replace(/[##]/g,"") // prints "12345"
str.replace(/\D/,"") // prints "123#45" => removes any non-digit, first occurrence
str.replace(/\D/g,"") // prints "12345" => removes any non-digit, all occurrence
g stands for global search
[##] stands for either # or #, you can add anything here
\D stands for anything other than digits

Related

how to find the first number from string in js(javascript)? [duplicate]

This question already has answers here:
Get the first integers in a string with JavaScript
(5 answers)
Closed 6 months ago.
How to find the first number from string in javascript?
var string = "120-250";
var string = "120,250";
var string = "120 | 250";
Here is an example that may help you understand.
Use the search() method to get the index of the first number in the string.
The search method takes a regular expression and returns the index of the first match in the string.
const str = 'one 2 three 4'
const index = str.search(/[0-9]/);
console.log(index); // 4
const firstNum = Number(str[index]);
console.log(firstNum); // 2
Basic regular expression start of string followed by numbers /^\d+/
const getStart = str => str.match(/^\d+/)?.[0];
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));
Or parseInt can be used, but it will drop leading zeros.
const getStart = str => parseInt(str, 10);
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));

Replace nth occurence of number in string with javascript [duplicate]

This question already has answers here:
Find and replace nth occurrence of [bracketed] expression in string
(4 answers)
Closed 5 years ago.
This question been asked before, but I did not succeed in solving the problem.
I have a string that contains numbers, e.g.
var stringWithNumbers = "bla_3_bla_14_bla_5";
I want to replace the nth occurence of a number (e.g. the 2nd) with javascript. I did not get farer than
var regex = new RegExp("([0-9]+)");
var replacement = "xy";
var changedString = stringWithNumbers.replace(regex, replacement);
This only changes the first number.
It was suggested to use back references like $1, but this did not help me.
The result should, for example, be
"bla_3_bla_xy_bla_5" //changed 2nd occurence
You may define a regex that matches all occurrences and pass a callback method as the second argument to the replace method and add some custom logic there:
var mystr = 'bla_3_bla_14_bla_5';
function replaceOccurrence(string, regex, n, replace) {
var i = 0;
return string.replace(regex, function(match) {
i+=1;
if(i===n) return replace;
return match;
});
}
console.log(
replaceOccurrence(mystr, /\d+/g, 2, 'NUM')
)
Here, replaceOccurrence(mystr, /\d+/g, 2, 'NUM') takes mystr, searches for all digit sequences with /\d+/g and when it comes to the second occurrence, it replaces with a NUM substring.
var stringWithNumbers = "bla_3_bla_14_bla_5";
var n = 1;
var changedString = stringWithNumbers.replace(/[0-9]+/g,v => n++ == 2 ? "xy" : v);
console.log(changedString);

How can I extract only the integer from a String JavaScript [duplicate]

This question already has answers here:
How to find a number in a string using JavaScript?
(9 answers)
Closed 6 years ago.
I have a string that looks like:
var a = "value is 10 ";
How would I extract just the integer 10 and put it in another variable?
You could use a regex:
var val = +("value is 10".replace(/\D/g, ""));
\D matches everything that's not a digit.
you can use regexp
var a = "value is 10 ";
var num = a.match(/\d+/)[0] // "10"
console.log ( num ) ;
You can use some string matching to get an array of all found digits, then join them together to make the number as a string and just parse that string.
parseInt(a.match(/\d/g).join(''))
However, if you have a string like 'Your 2 value is 10' it will return 210.
You do it using regex like that
const pattern = /\d+/g;
const result = yourString.match(pattern);

Count number of times a character appears in string [duplicate]

This question already has answers here:
Count number of occurrences for each char in a string
(23 answers)
Closed 6 years ago.
So basically I need a script that summarizes which characters and the number of times they appear in a random string. Caps have to be ignored, for example:
var myString = promt ("Type anything: "); //"hello Hello";
The end result has to be something like this: h = 2, e = 2, l = 4, o = 2 printed in the HTML document.
I've tried using myString.match().length without much success. My main problem is defining which characters to check and not checking characters twice (for example: if there are two "h" in the string not checking them twice).
You can use temporary object
var o = {};
"hello Hello".toLowerCase()
.replace(/\s+/, '')
.split('')
.forEach(e => o[e] = ++o[e] || 1);
document.write(JSON.stringify(o));
This solution uses arrow function (ES2015 standard) that doesn't work in old browsers.
var str = 'hello Hello';
var count = {};
str.split('').forEach(function(v) {
if (v === ' ') return;
v = v.toLowerCase();
count[v] = count[v] ? count[v] + 1 : 1;
})
console.log(count);

How can I parse a string and split it into two parts at a special character with javascript? [duplicate]

This question already has answers here:
How do I split a string, breaking at a particular character?
(17 answers)
Closed 8 years ago.
How can I take a string and split it at a special character into two new variables (and remove the special chars) with javascript?
For example take:
var X = Peggy Sue - Teacher
and turn it into:
varnew1 = Peggy Sue
varnew2 = Teacher
I guess it should also include a condition... if the string has a "-" then do this.
.split is probably what you want. Here is a very simple example
JSFiddle Link
var string = 'Peggy Sue - Teacher'
var new1 = string.split('-')[0].trim();
var new2 = string.split('-')[1].trim();
console.log(new1); // "Peggy Sue"
console.log(new2); // "Teacher"
And if you want to place a simple condition on it looking for - you can do so with the following
var string = 'Peggy Sue - Teacher'
var new1 = string.indexOf('-') !== -1 ? string.split('-')[0].trim() : string
var new2 = string.indexOf('-') !== -1 ? string.split('-')[1].trim() : string
Second Fiddle
var result = str.split("-");
will give you an array with 2 members,
result[0] = Peggy Sue
result[1] = Teacher

Categories

Resources