Data Replace is not working - javascript

var data = this.state.registerMobile;
//My data will be like +91 345 45-567
data.replace('-','');
It is not removing '-' and i am trying to remove spaces also in between.It's not working.

For that, you need to assign the result of replace to some variable, replace will not do the changes in same variable, it will return the modified value. So use it like this:
var data = this.state.registerMobile;
data = data.replace('-', '');
console.log('updated data', data);
Check the example:
a = '+91 12345678';
b = a.replace('+', '');
console.log('a', a );
console.log('b', b );

String.prototype.replace() does not change the original string but returns a new one. Its first argument is either of the following:
regexp (pattern)
A RegExp object or literal. The match or matches are replaced with newSubStr or the value returned by the specified function.
substr (pattern)
A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.
So if you want to replace hypens and whitespaces, you have to use the following:
var data = this.state.registerMobile;
data = data.replace(/\s|-/g, '');

Related

regex to ignore special characters

Say, I have a text stored as:
var val1 = 'l-oreal';
I want to match val1 such that, it reads val1 and ignores hyphen (dash) in it. I want a regex that ignores special characters in a text. Is that possible?
I don't want to remove special character from the text. I want to ignore it.
You can match against the regex /[a-z]+/gi and then join by a space or any other character:
var testString = "any string l-orem";
var matcher = /[a-z]+/gi;
var matches = testString.match(matcher);
var result = matches.join('');
console.log(result);
This, of course, doesn't change your original string, and can be simply customized to your own needs.
You can either use ^ in order to select your special characters then replace it to an empty string '', as:
val1.replace(/([^a-zA-z0-9]+)/g, s0 => ''); // loreal
All except a-zA-Z-0-9 will be removed.
Updated post for scenario when:
The string must contain characters abc and ignore any special
characters
for this approach, you could make use of match to know if your string has any matches on your regex. If so, then you could use replace to switch special chars to empty string:
function strChecker(str) {
var response;
if(val1.match(/lorem/)) {
response = val1.replace(/([^a-zA-z0-9]+)/g, s0 => '');
}
return response;
}
strChecker('ha-ha?lorem') // returns hahalorem
strChecker('ha-ha?loram') // return undefined
var val1 = 'l-oreal';
var val2 = val1.replace(/\W/g,''); // remove any non-alphanumerics
console.log(val1); // still the same, not changed
console.log(val2); // only alphanumerics

Using RegExp to substring a string at the position of a special character

Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);

Javascript - How to use replace() function properly

I am willing to do the following:
I have :
var distance1 = "5.5 Km";
var distance2 = "5,5 Km";
//The below works as expected and returns 5.5
var finalDistance = distance1.replace( /[^\d\.]*/g, '');
//However the below doesn't and print 55 instead
distance2.replace( /[^\d\.]*/g, '');
//I've tried the below too and it throws 5,5. But I want 5.5
distance2.replace( /[^\d\.\,]*/g, '');
First, replace all occurences of , with ., then replace non-digit characters (except .) with '':
distance2 = distance2.replace( /,/g, '.').replace(/[^\d\.]+/g, '');
where:
/,/g : matches all commas ',' that will be replaced by '.'
/[^\d\.]+ : matches any sequence of non-digit and non-dot ('.') characters that will be removed (replaced by the empty string '').
The first replace transform "5,55 KM" to "5.55 KM" then the second transform the latter to "5.55".
Note: if you only have one comma, or only interested in the first encountered one, then you could use: replace(',', '.') instead of replace(/,/g, '.').
If you are using only the float representation, you could use parseFloat instead of the second replace:
var number = parseFloat(distance2.replace(/,/g, '.'));
replace works by saying "find this string and replace with this string". The first parameter is what you want to find, the second is what to replace it with. So in your code you're replacing the , with nothing:
distance2.replace( /[^\d\.]*/g, '');
It also doesn't edit the string "in-place", so you need to assign the distance2 variable to the return value. Also, for a simple job like this you don't need to use regex. You can just input a string as the first parameter and replace will find all matches for that. This is how I would do this:
distance2 = distance2.replace(',', '.');
Further reading:
https://www.w3schools.com/jsref/jsref_replace.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace
you need to reassign the replace value to the variable.
i.e.
distance2 = distance2.replace( /[^\d\.]*/g, '');

Replace in javascript

I have a string something like this:
http://stackoverflow.com/questions/ask
And would like to return this part:
http://stackoverflow.com/questions/
How can I do this using pure javascript?
Thanks!
This will match and remove the last part of a string after the slash.
url = "http://stackoverflow.com/questions/ask"
base = url.replace(/[^/]*$/, "")
document.write(base)
Help from: http://www.regexr.com/
For slicing off last part:
var test = 'http://stackoverflow.com/questions/ask';
var last = test.lastIndexOf('/');
var result = test.substr(0, last+1);
document.write(result);
You can accomplish this with the .replace() method on String objects.
For example:
//Regex way
var x = "http://stackoverflow.com/questions/ask";
x = x.replace(/ask/, "");
//String way
x = x.replace('ask', "");
//x is now equal to the string "http://stackoverflow.com/questions/"
The replace method takes two parameters. The first is what to replace, which can either be a string or regex, literal or variable, and the second parameter is what to replace it with.

Extract a value from json inside json string

var a = '{"test_cmd": "pybot -args : {\"custom-suite-name\" : \"my-1556\"}}'
b = a.match("\"custom-suite-name\" : \"([a-zA-Z0-9_\"]+)\"")
console.log(b)
I have a json string inside json string.
I like to extract the property custom-suite-name's value using the regex.
Output must be,
my-1556.
But the return value b has no matches/null value.
Don't use a regexp to parse JSON, use JSON.parse.
var obj = JSON.parse(a);
var test_cmd = obj.test_cmd;
var args_json = test_cmd.replace('pybot -args : ', '');
var args = JSON.parse(args_json);
var custom_suite = args.custom_suite_name;
It's better to put your regex within / slashes. NOte that,
There is a space exists before colon.
No need to escape double quotes.
Include - inside the character class because your value part contain hyphen also.
Code:
> a.match(/"custom-suite-name" : "([a-zA-Z0-9_-]+)"/)[1]
'my-1556'
> a.match(/"custom-suite-name"\s*:\s*"([a-zA-Z0-9_-]+)"/)[1]
'my-1556'

Categories