Use match in replace [duplicate] - javascript

This question already has answers here:
Javascript string replace method. Using matches in replacement string
(2 answers)
Closed 3 years ago.
I need to put every non-alphabetic character between spaces.
I want to do this using RegExp, and I understand it enouch to select them all (/(^a-zA-Z )/g).
Is there a way to use the original match inside the replace?
(something like)
str.replace(/(^a-zA-Z )/g,/ \m /);
If not I will just loop over all of them, but I really want to know it it is possible.

Yes. You can give the String.prototype.replace() function a RegExp as it's search. You can also give it a function to handle replacing.
The function will give you the match as the first parameter, and you return what you want to change it to.
const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, match => ` ${match} `);
console.log(replaced);
If you just need to do something simple, you can also just use the $n values ($1, $2, etc) to replace based on the selected group (the sets of parentheses).
const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, ' $1 ');
console.log(replaced);

Yes, it is possible. You can use regex with group:
var text = '2apples!?%$';
var nextText = text.replace(/([^a-zA-Z])/g, ' $1 ');
console.log(nextText);

You can check replace function on this link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Related

How to remove thousand separaters in number using javascript? [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 2 years ago.
problem:
I want to remove the comma in a string and make it as a number.
It means,
234,345 should become 234345.
1,234 should become 1234
4,567,890 should become 4567890
I have created one code like this.
let a = "5,245"
function numberWithoutCommas(x) {
return x.replace(",","");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
This is failing when there more comma in the string.It means 1,234,567 gives 1234. So can someone help me to achieve it?
Splitting and joining should do the job
return x.split(',').join('');
You can simply parse to a number and use a regex
const s = ['5,332', '39,322,322,233']
function numberWithoutCommas(x) {
return Number(x.replace(/,/g, ''));
}
for (const a of s) {
const n = numberWithoutCommas(a);
console.log(n, typeof n);
}
passing string as a first argument to replace method will only replace the very first occurrence.
let str = '111,11,11,1';
str.replace(',','') // result:- 11111,11,1
use regex instead
str.replace(/,/g,'') //result:- 11111111
in your use case
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}
The replace() method searches a string for a specified value, or a
regular expression, and returns a new string where the specified
values are replaced.
Note: If you are replacing a value (and not a regular expression),
only the first instance of the value will be replaced. To replace all
occurrences of a specified value, use the global (g) modifier.
So, to replace all the occurrences of ,, we should rather use /,/g instead of just ,.
Then your code would be something like the following
let a = "1,234,567"
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
I hope this helps :)

Javascript Regex - Match everything after string [duplicate]

This question already has answers here:
Remove querystring from URL
(11 answers)
Closed 6 years ago.
I'm trying to use JS regex to drop everything after a string in my url. For example www.myurl/one/two/three/?a=b&c=d I want to drop everything after the string "three/". How would I write a regex to match this?
Try this one:
function getPathFromUrl(url) {
return url.split("?")[0];
}
var url = 'www.myurl/one/two/three/?a=b&c=d';
var result = getPathFromUrl(url);
alert(result);
Here's one quick way.
var str = 'www.myurl/one/two/three/?a=b&c=d'
var newStr = str.replace(/(.*\/three\/).*/, '$1')
alert(newStr)
Use built-in ability to manipulate URLs.
var a = document.createElement('a');
a.href = "http://www.myurl/one/two/three/?a=b&c=d";
a.search = '';
console.log(a.href);
Notes:
The search property of the a element refers to the portion starting with the question mark.
The http:// is required here; otherwise, the URL will be interpreted as relative to the current URL.
If you would prefer to use a regexp, then you could erase everything starting with the question mark:
"www.myurl/one/two/three/?a=b&c=d".replace(/\?.*/, '')
Or, you could match what you DO want to keep, such as everything up to the question mark, using:
"www.myurl/one/two/three/?a=b&c=d".match(/.*(?=\?)/)[0]
You need the [0] since match returns an array, whose first element is the entire match. The ?= here is a look-ahead. Actually that is the same as
"www.myurl/one/two/three/?a=b&c=d".match(/[^?]+/)[0]
Or, if you want to match up to three/ specifically:
"www.myurl/one/two/three/?a=b&c=d".match(/.*three\//)[0]
Or basicaly with methods of String and Array :
var string = "www.myurl/one/two/three/?a=b&c=d";
var array = string.split('/');
array.pop();
var result = array.join("/");
console.log(result); //www.myurl/one/two/three

simple regular expression with equals but dont want to use split [duplicate]

This question already has answers here:
Regular Expressions in JavaScript for URL Capture
(4 answers)
Closed 7 years ago.
I have the message string as follows.
string=052
I need to use regular expression not split.
I want to return everything past the equals. 052
This is what i tried and gives me id=null
var regex = '[^?string=]';
var id2 = mystring.match(regex);
I have tried online regex checkers and it looks like it matches all but the a
is there a better reg ex i should try? id should not equal null.
You're using String.match() incorrectly. Try this:
var regex = '^message=(.*)$';
var id = queryString.match(regex)[1];
.match() returns an array; the first element (at [0]) is the entire matched string, and the second element (at [1]) is the part that's matched in the (first) set of parentheses in the regex.

replace '\n' in javascript [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Fastest method to replace all instances of a character in a string [duplicate]
(14 answers)
Closed 1 year ago.
I'm trying to do replace in JavaScript using:
r = "I\nam\nhere";
s = r.replace("\n"," ");
But instead of giving me
I am here
as the value of s,
It returns the same.
Where's the problem??
As stated by the others the global flag is missing for your regular expression. The correct expression should be some thing like what the others gave you.
var r = "I\nam\nhere";
var s = r.replace(/\n/g,' ');
I would like to point out the difference from what was going on from the start.
you were using the following statements
var r = "I\nam\nhere";
var s = r.replace("\n"," ");
The statements are indeed correct and will replace one instance of the character \n. It uses a different algorithm. When giving a String to replace it will look for the first occurrence and simply replace it with the string given as second argument. When using regular expressions we are not just looking for the character to match we can write complicated matching syntax and if a match or several are found then it will be replaced. More on regular expressions for JavaScript can be found here w3schools.
For instance the method you made could be made more general to parse input from several different types of files. Due to differences in Operating system it is quite common to have files with \n or \r where a new line is required. To be able to handle both your code could be rewritten using some features of regular expressions.
var r = "I\ram\nhere";
var s = r.replace(/[\n\r]/g,' ');
use s = r.replace(/\\n/g," ");
Get a reference:
The "g" in the javascript replace code stands for "greedy" which means the replacement should happen more than once if possible
The problem is that you need to use the g flag to replace all matches, as, by default, replace() only acts on the first match it finds:
var r = "I\nam\nhere",
s = r.replace(/\n/g,' ');
To use the g flag, though, you'll have to use the regular expression approach.
Incidentally, when declaring variables please use var, otherwise the variables you create are all global, which can lead to problems later on.
.replace() needs the global match flag:
s = r.replace(/\n/g, " ");
It's working for me:
var s = r.split('\\n').join(' ');
replaceAll() is relative new, not supported in all browsers:
r = "I\nam\nhere";
s = r.replaceAll("\n"," ");
You can use:
var s = r.replace(/\n/g,' ').replace(/\r/g,' ');
because diferents SO use diferents ways to set a "new line", for example: Mac Unix Windows, after this, you can use other function to normalize white spaces.
Just use \\\n to replace it will work.
r.replace("\\\n"," ");
The solution from here worked perfect for me:
r.replace(/=(\r\n|\n|\r)/gm," ");

javascript - split without losing the separator [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Split without losing character
I have a string:
"<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>"
I want to separate all instances of "abcdefg" into an array like this:
["<foo>abcdefg</bar>", "<foo>abcdefg</bar>", "<foo>abcdefg</bar>", "<foo>abcdefg</bar>"];
I try:
var str="<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>";
var Array_Of_FooBars = str.split("</bar>");
alert(Array_Of_FooBars);
But it returns:
["<foo>abcdefg", "<foo>abcdefg", "<foo>abcdefg", "<foo>abcdefg",]
It is removing the separator ''. I don't want that.
How can I use split and not lose the separators from the string?
Thanks.
Ken
Try this. It's not a perfect solution, but it should work in most cases.
str.split(/(?=<foo>)/)
That is, split it in the position before each opening tag.
EDIT: You could also do it with match(), like so:
str.match(/<foo>.*?<\/bar>/g)
It seems that you would most likely want to use match:
var s = "<foo>abcd1efg</bar><foo>abc2defg</bar><foo>abc3defg</bar><foo>abc4defg</bar>"
s.match(/(<foo>.+?<\/bar>)/g)
// =>["<foo>abcd1efg</bar>", "<foo>abc2defg</bar>", "<foo>abc3defg</bar>", "<foo>abc4defg</bar>"]
You could just iterate over a simple regular expression and build the array that way:
var x = new RegExp('<foo>(.*?)</bar>', 'ig'),
s = "<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>",
matches = [];
while (i = x.exec(s)) {
matches.push(i[0]);
}
Just realized using String.match() would be better; this code would be more useful for matching the contents inside the tags.
Use positive lookahead so that the regular expression asserts that the special character exists, but does not actually match it:
string.split(/<br \/>(?=&#?[a-zA-Z0-9]+;)/g);

Categories

Resources