Javascript:How to remove occurrence of a character from a value? - javascript

Here i am trying to replace an occurrence of a string and 4 characters after that by blank.
For Eg i have the below string:
var a=ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG
I get the value as bvbfg
Now when i get the value i should replace bvbfg~JJJ to blank value and the string should become
var a=ssss~ABC*ertert~PMU*trert~GFRG*qqqq~hghgh
Similarly if i get the value as qqqq i should replace qqqq~HGHGHG to blank value
and the new value should be
var a=ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG
I tried making using of regular expression:
Something as below(For Eg)
mystring.replace(/bvbfg/g , "newchar");
But the results i saw were not good. It is a bit tricky. Any guidance. Thanks.

function remove(str, tok) {
var regex = new RegExp('\\b' + tok + '~[^*]*\\*?', 'i'); // if you want it to be case sensetive, then remove the 'i' parameter
return str.replace(regex, '')
/*.replace(/^\*|\*$/, '')*/; // uncomment this to remove *s from the start and the end
}
var a = "ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG";
console.log(remove(a, "ertert"));
Parse:
function parse(str) {
return str.split('*')
.reduce(function(res, e) {
var parts = e.split('~');
res[parts[0]] = parts[1];
return res;
}, {});
}
var a = "ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG";
console.log(parse(a));

I am new to regex, this is what I tried and it seems to work.
/bvbfg~(\w+)[*]?/g
Demo: http://regexr.com/3fagf
But I would suggest you to use Wiktor Stribiżew's answer.

Here you go... short and simple :)
document.getElementById('btn').onclick = function() {
var value = document.getElementById('value').value,
a = 'ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG',
regx = new RegExp('\\*?' + value + '~\\w*', 'g');
console.log(a.replace(regx, ''));
}
<input id="value" type="text">
<button id="btn">Submit</button>

Putting everything together with Stribiżew's regex:
function getRegexp(s) {
return new RegExp( s + '~[^*]*\\*?', 'gi');
}
var str = 'ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG';
var s = 'bvbfg';
console.log(str.replace(getRegexp(s), ''));
s = 'qqqq';
console.log(str.replace(getRegexp(s), ''));

Related

Regular expression not capturing multiple characters [duplicate]

I have a string in JavaScript (e.g., #box2), and I just want the 2 from it.
I tried:
var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);
It still returns #box2 in the alert. How can I get it to work?
It needs to accommodate for any length number attached on the end.
For this specific example,
var thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing
In the general case:
thenum = "foo3bar5".match(/\d+/)[0] // "3"
Here's a bonus: regex generator.
function getre(str, num) {
if(str === num)
return 'nice try';
var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g];
for(var i = 0; i < res.length; i++)
if(str.replace(res[i], '') === num)
return 'num = str.replace(/' + res[i].source + '/g, "")';
return 'no idea';
};
function update() {
$ = function(x) { return document.getElementById(x) };
var re = getre($('str').value, $('num').value);
$('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>
You should try the following:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​
Result
1234561613213213
I think this regular expression will serve your purpose:
var num = txt.replace(/[^0-9]/g, '');
Where txt is your string.
It basically rips off anything that is not a digit.
I think you can achieve the same thing by using this as well:
var num = txt.replace(/\D/g, '');
Try the following: string.replace(/[^0-9]/g, ''); This will delete all non-digit characters, leaving only digits in the string
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
return parseInt(num,10);
}
console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));
console.log('#box2'.replace(/[^0-9]/g, ''));
Using the match function.
var thenum = "0a1bbb2".match(/\d+$/)[0];
console.log(thenum);
And this is a snippet which extracts prices with currency and formatting:
var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
I tried all the combinations cited in the previous answer with this code and got it working. It was the only one that worked on that string → (12) 3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
Result: "1234567890"
Obs: I know that a string like that will not be on the attribute, but whatever, the solution is better, because it’s more complete.
You may use the great parseInt() method.
It will convert the leading digits to a number:
parseInt("-10px");
// Will give you -10
You can extract numbers from a string using a regex expression:
let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);
Output: 25933473
Wrap it into a vanilla JavaScript function:
function onlyNumbers(text){
return text.replace(/\D/g, "");
}
For a string such as #box2, this should work:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
http://jsfiddle.net/dmeku/
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
console.log(justNumbers('abcdefg12hijklmnop'));
You can do a function like this
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
Remember: if the number has a zero in front of it, the int won’t have it
If you want to parse a number from a price like $6,694.20, it can be done this way:
parseFloat('$6,694.20'.replace(/^\D|,+/g, ''))
Or via a function:
function parsePrice(value) {
return parseFloat(value.replace(/^\D|,+/g, ''))
}
parsePrice('$6,694.20') // 6694.2
To return an int from the string, you can do the following code. It removes all not number characters and returns an integer.
Number("strin[g]3".replace(/\D+/g, ""))
You can use a regular expression.
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.
let str = "Total Work Duration: 189.56 Hrs.Present: 23.5 Absent: 2";
/* The provided regex globally matches the character
"." and a digit from the string */
let numArr = str.match(/[\d\.]+/g)
/* It returns an array [189.56, ., 23.5, 2], and
uses the filter function to remove the '.' */
numArr = numArr.filter(n => n != '.')
console.log(numArr)
If someone need to preserve dots in extracted numbers:
var some = '65,87 EUR';
var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
console.log(number); // returns 65.87
You can use Underscore.js' string library as follows:
var common = "#box"
var href = "#box1"
_(href).strRight(common)
The result will be: 1
See: Underscore.string
Demo:
http://jsfiddle.net/abdennour/Vyqtt/
HTML code:
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JavaScript code:
var comm = "#box"
$('a').click(function() {
$('div').html(_($(this).attr('href')).strRight(comm))})
If you have a suffix as follows:
href="box1az"
You can use the following demo:
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all, prefix, suffix) {
var left = _(all).strRight(prefix);
return _(left).strLeft(suffix);
}
Here's a solution that checks for no data:
var someStr = 'abc'; // Add 123 to string to see the inverse
var thenum = someStr.match(/\d+/);
if (thenum != null)
{
console.log(thenum[0]);
}
else
{
console.log('Not a number');
}
var elValue = "-12,erer3 4,-990.234sdsd";
var isNegetive = false;
if(elValue.indexOf("-") == 0)
isNegetive = true;
elValue = elValue.replace( /[^\d\.]*/g, '');
elValue = isNaN(Number(elValue)) ? 0 : Number(elValue);
if(isNegetive)
elValue = 0 - elValue;
alert(elValue); // -1234990.234
With regular expressions, how to get numbers from a string, for example:
String myString = "my 2 first gifts were made by my 4 brothers";
myString = myString.replaceAll("\\D+", "");
System.out.println("myString: " + myString);
The result of myString is "24".
You can see an example of this running code at http://ideone.com/iOCf5G.
Use this one-line code to get the first number in a string without getting errors:
var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
Please check the below JavaScript code. There you can get only a number.
var txt = "abc1234char5678#!9";
var str = txt.match(/\d+/g, "") + '';
var s = str.split(',').join('');
alert(Number(s));
Output: 1234567789
You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:
var color = $( this ).css( "background-color" );
var r = parseInt(color.match(/\d+/g)[0]);
var g = parseInt(color.match(/\d+/g)[1]);
var b = parseInt(color.match(/\d+/g)[2]);
This answer will cover most of the scenarios. I came across this situation when a user tried to copy paste the phone number.
$('#help_number').keyup(function() {
$(this).val().match(/\d+/g).join("")
});
Explanation:
str = "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give an array of strings as output:
["34", "56766"]
 
str.match(/\d+/g).join("")
join() will convert and concatenate that array data into a single string.
Output:
"3456766"
In my example, I needed the output as 209-356-6788, so I used replace():
$('#help_number').keyup(function() {
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/, '$1-$2-$3'))
});
Written without a regular expression:
// Without Regex
function extractNumber(string) {
let numArray = string.split('').map(item => {
if (typeof +item === 'number' && !isNaN(+item))
return +item
})
return +numArray.join('')
}
extractNumber('#1200milion$') // 1200
In one of my projects I had to take a rating value from a string. This is what I used:
let text = '#xbox2'
let num = text.trim().
split('').
map(num => Number(num)).
filter(x => Number.isInteger(x))
Use:
changeStrangeDate(dateString: string) {
var sum = 0;
var numbers = dateString.match(/\d+/g);
if (numbers.length > 1) {
numbers.forEach(element => {
sum += parseInt(element);
}
);
}
console.log(new Date(sum).toDateString());
return new Date(sum).toUTCString();
}
You can do it like that and then call a function where you need it, with a parameter.
this.changeStrangeDate('/Date(1551401820000-0100)/');

Using simple angular filter to replace all occurences of certain strings in input string regardless of case and whitespaces

On my website I have a commentary field, where people can write whatever they want. To prevent spam and unserious comments, I'm using an angular filter in this way:
<span>{{comment | mouthWash}}</span>
The angular filter fetches an array containing banned words and scans through the input string and replaces all the occurences of the fetched words. The code for the filter is as below:
app.filter('mouthWash', function($http) {
var badWords;
$http.get('js/objects/bad-words.json').success(function (data) {
badWords = data;
});
return function(input) {
angular.forEach(badWords, function(word){
var regEx = new RegExp(word);
input = input.replace(regEx, "mooh");
});
return input;
};
});
bad-words.json is something like this:
["fuck", "ass", "shit", etc...]
So as an example <span>{{ "fuck this" | mouthWash}}</span> is outputted as <span>mooh this</span>
This is working perfectly, except that I want it to ignore whitespaces, to make it more bullet proof. I do not have much experience with regex, so if anyone had a simple soloution to this, I would be really grateful.
just change new RegExp(word, "ig"); to new RegExp("ig");
working example:
var words = ['pig', 'dog', '', ' ', 'cow'];
words.forEach(function(word) {
var regEx = new RegExp("ig");
word = word.replace(regEx, "mooh");
console.log(word);
});
Output:
"pmooh"
"dog"
""
" "
"cow"
This is the code I ended up with:
app.filter('mouthWash', function($http) {
var badWords;
$http.get('js/objects/bad-words.json').success(function (data) {
badWords = data;
});
return function(input) {
angular.forEach(badWords, function(word){
var str = word.substring(0,1)+"\\s*";
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*";
str = str + word.substring(word.length - 1,word.length);
var regEx = new RegExp(str, "gi");
input = input.replace(regEx, "mooh");
});
return input;
};
});
I created a for loop that would loop through every character of the banned word, adding the character together with \s* (so that spaces was ignored) to a string.
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*";
Then created a regExp from the string, by using the regExp constructor with the string as first parameter and "gi" as second, to make the regExp global and case insensitive.
var regEx = new RegExp(str, "gi");
Then that regex was used to search through input string and replace all matches with "mooh".

How can we split a string using starts with regular expression (/^myString/g)

I am having a case where i need to split given string using starts with regex (/^'searchString'/) which is not working such as
"token=123412acascasdaASDFADS".split('token=')
Here i want to extract the token value but as there might be some other possible parameters such as
"reset_token=SDFDFdsf12313ADADF".split('token=')
Here it also split the string with 'token=', Thats why i need to split the string using some regex which states that split the string where it starts with given string.
Thanks..
EDITED
Guys thanks for your valuable response this issue can be resolve using /\btoken=/ BUT BUT its does not work if 'token=' stored as a string into a variable such as
sParam = 'token=';
"token=123412acascasdaASDFADS".split(/\bsParam/);
This does not works.
You can use regex in split with word boundary:
"token=123412acascasdaASDFADS".split(/\btoken=/)
If token is stored in a variable then use RegExp constructor:
var sParam = "token";
var re = new RegExp("\\b" + sParam + "=");
Then use it:
var tokens = "token=123412acascasdaASDFADS".split( re );
This is the use case for the \b anchor:
\btoken=
It ensures there's no other word character before token (a word character being [a-zA-Z0-9_])
You need to split the string using the & parameter delimiter, then loop through those parameters:
var token;
$.each(params.split('&'), function() {
var parval = this.split('=');
if (parval[0] == "token") {
token = parval[1];
return false; // end the $.each loop
}
});
if you just use token= as the split delimiter, you'll include all the other parameters after it in the value.
It's not clear what you need, but this may be an idea to work with?
var reqstr = "token=12345&reset_token=SDFDFdsf12313ADADF&someval=foo"
.split(/[&=]/)
,req = [];
reqstr.map( function (v, i) {
if (i%2==0) {
var o = {};
o[/token/i.test(v) ? 'token' : v] = reqstr[i+1];
this.push(o);
} return v
}, req);
/* => req now contains:
[ { token: '12345' },
{ token: 'SDFDFdsf12313ADADF' },
{ someval: 'foo' } ]
*/
You can try with String#match() function and get the matched group from index 1
sample code
var re = /^token=(.*)$/;
var str = 'token=123412acascasdaASDFADS';
console.log('token=123412acascasdaASDFADS'.match('/^token=(.*)$/')[1]);
output:
123412acascasdaASDFADS
If token is dynamic then use RegExp
var token='token=';
var re = new RegExp("^"+token+"(.*)$");
var str = 'token=123412acascasdaASDFADS';
console.log(str.match(re)[1]);
Learn more...

How to remove the comma(,) from the first position and last position of string

I want to remove the comma(,) from the the string if it occur at first position or last position in the string.
For Example :
var str = ",abcd,efg,last,";
The output should be
output = 'abcd,efg,last'
if input is
str = "abcdef,ghij,kl"
the output should be :
output = "abcdef,ghij,kl"
var str = ",abcd,efg,last,";
var res = str.replace(/^,|,$/g, '');
console.log(res);
do this
this will remove the comma if it is at the starting position or at the end of the string position
There must be some strip() function in Javascript that I don't know for lack of my knowledge. But here is how you can do it using regex:
output = ",abcd,efg,last,".replace(/^,|,$/g, "");
JavaScript doesn't include a native method for this. The closest is trim, but that doesn't take any args. I think it should, though. So you could write something like this
String.prototype.trim = (function (trim) {
if (!trim) // polyfill if not included in browser
trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
else if (trim.call('.', '.') === '') // already supports this
return trim;
return function (chars) {
if (!chars) return trim.call(this);
chars = chars.replace(/([\^\\\]-])/g, '\\$1');
return this.replace(new RegExp('^['+chars+']+|['+chars+']+$', 'g'), '');
}
}(String.prototype.trim));
Now we have
' foo '.trim(); // "foo"
',,,foo,,,'.trim(','); // "foo"

Remove a letter(:) from a string

I have strings like Name:, Call:, Phone:....and so on in my table. I am learning jQuery and was able to access the text. My tutorial has used trim() to remove any whitespaces. But I want o remove ":" from the end of each string (and yes, it always lies in the end after calling trim() method). So how to achieve it.
Its my code:
<script type="text/javascript">
$(function ()
{
$(':input[type=text], textarea').each
(
function ()
{
var newText = 'Please enter your ' +
$(this).parent().prev().text().toLowerCase().trim();
$(this).attr('value', newText);
}).one('focus', function ()
{
this.value = '', this.className = ''
}).addClass('Watermark').css('width', '300px');
});
</script>
trim(":") did not help...
You can replace all : characters:
var str = '::a:sd:';
str = str.replace(/:/g,''); // str = 'asd';
Or use a handy rtrim() function:
String.prototype.rtrim = function(character) {
var re = new RegExp(character + '*$', 'g');
return this.replace(re, '');
};
var str = '::a:sd:';
str = str.rtrim(':'); // str = '::a:sd';
In this case just use the plain old JavaScript replace or substr methods.
You can also use a regular expression that looks for colon as the last character (the character preceding the regexp end-of-string anchor "$").
"hi:".replace(/:$/, "")
hi
"hi".replace(/:$/, "")
hi
"h:i".replace(/:$/, "")
h:i
This is a simplified, inline version of the rtrim function in Blender's answer.
EDIT: Here is a test fiddle for Blender's corrected rtrim function. Note that his RegExp will delete multiple occurrences of the specified character if the string ends with multiple instances of it consecutively (example bolded below).
http://jsfiddle.net/fGrPb/5/
input = '::a:sd:' output = '::a:sd'; input = 'hi:' output = 'hi'; input = 'hi:::' output = 'hi'; input = 'hi' output = 'hi'; input = 'h:i' output = 'h:i'
To chop the last character of a string use string.slice(0,-1)
You can use a regular expression to remove the colon (:).
Replace one instance:
var with_colon = 'Stuff:';
var regex = /([^:]*):/;
var without_colon = regex.exec(with_colon)[1];
alert(without_colon);
Result: Stuff
Replace all instances:
var with_colon = 'Stuff: Things:';
var without_colon = with_colon.replace(/([^:]*):/g,'$1');
alert(without_colon);
Result: Stuff Things
var myStr = "something:";
myStr = myStr.slice(0, -1);
var a="name:";
var b=a.split(":");
alert(b[0]);
one way is to use lastIndexOf
var str='Name:, Call:, Phone:';
var index=str.lastIndexOf(":");
alert(index);
var s=str.substring(0,index);
alert(s);
DEMO
This checks if the last character is a colon. If it is, the last character is removed.
if (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
If there can be multiple trailing colons, you can replace if with while, like this:
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
You could even make a generic trim function that accepts a string and a character and trims trailing instances of that character:
var trim = function(str, chr) {
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
return str;
}
function trim(str) {
str = str.replace(/^:*/,"");
return str.replace(/:*$/,"");
}
str = str.substring(0,str.lastIndexOf(":"));
Note that this removes everything from the last : to the end of the string (for example, any whitespace after the :).

Categories

Resources