Remove ONLY a Single instance of a character from a String Javascript - javascript

I have a string "QAWABAWONL", from which I want to remove ONLY a single occurrence of the character 'A'. It does not matter whether the first occurrence or the second occurrence gets removed, either is fine. I've found that using indexOf or includes removes all occurrences.

I'ts simple, there are many ways of doing this. I would use a regex:
myStr.replace(/A/i, "");
The i flag is for ignoring case. If you wanted to replace more than one occurrence you need the g flag but it's not your case.

Use String.replace and pass a substring for the first argument.
From the above link (emphasis mine):
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.
Usage:
let originalString = "QAWABAWONL";
let result = originalString.replace("A","");
console.log(result);

You can use regular expression in jscript, it's so easy:
example: alert("some text1, some tex2, some text3".replace('text1', ''));
Remove first occurrence of comma in a string
I hope it is useful !

Related

Deciphering contents of a .replace() parameter

In an example piece of code, I stumbled upon this line:
// Change the string into lower case and remove all non-alphanumeric characters
var cstr = str_entry.toLowerCase().replace(/[^a-zA-Z0-9]+/g,'');
I think I understand that the /g inside the parameter makes everything in between the // become empty strings (''). Am I correct?
What does the ^ part of the parameter do? What does everything inside the [ ] brackets mean?
The first parameter of the replace function is a regular expression, which is a way of determining if a string matches a complex pattern.
The /g parameter means 'global', so if two parts of the str_entry string match, they will both replaced with an empty string, instead of just the first one.
The ^ within [] means 'not', so it's saying 'check if the string is not a-zA-Z0-9'.
More simply, the regular expression is identifying any non-alphanumeric characters in your string. Using it with replace(..., '') will remove those characters.
Take a look at Regex101 for more information about how regular expressions work. You can punch in your regular expression and it will tell you what each part of it does.

Split ignoring part of regex

My goal is to get the length till the nth occurrence of <br> tag in javascript so I am splitting them up.
I am trying regex
((.|\s)*?<br\s?/?>){2} //2 is the max number of lines(br tags) allowed.
While this is working fine in regexBuddy
but the string is splitted into multiple parts ignoring the <br\s?/?> part in browser.
you can view a fiddle here
What am I doing wrong
Wouldn't exec make more sense than split in this case?
var str=$('#op').html();
var match = /((.|\s)*?<br\s?\/?>){2}/i.exec(str);
if( match )
console.log(match[0].length);
The issue is that you are using the split() method, which will split the string up in to pieces based on the regular expression. This will not include your regular expression match. In your case the first section of the string matches your regular expression, so you would have an empty string at index 0 and everything after the regular expression match in index 1.
You should try to use the match() method instead, which will return an array of the pieces of the string that matched your regular expression.
var str=$('#op').html();
console.log(str.match(/(([\s\S])*?<br\s?\/?>){2}/i)[0].length);
See code.

javascript regex to return letters only

My string can be something like A01, B02, C03, possibly AA18 in the future as well. I thought I could use a regex to get just the letters and work on my regex since I haven't done much with it. I wrote this function:
function rowOffset(sequence) {
console.log(sequence);
var matches = /^[a-zA-Z]+$/.exec(sequence);
console.log(matches);
var letter = matches[0].toUpperCase();
return letter;
}
var x = "A01";
console.log(rowOffset(x));
My matches continue to be null. Am I doing this correctly? Looking at this post, I thought the regex was correct: Regular expression for only characters a-z, A-Z
You can use String#replace to remove all non letters from input string:
var r = 'AA18'.replace(/[^a-zA-Z]+/g, '');
//=> "AA"
Your main issue is the use of the ^ and $ characters in the regex pattern. ^ indicates the beginning of the string and $ indicates the end, so you pattern is looking for a string that is ONLY a group of one or more letters, from the beginning to the end of the string.
Additionally, if you want to get each individual instance of the letters, you want to include the "global" indicator (g) at the end of your regex pattern: /[a-zA-Z]+/g. Leaving that out means that it will only find the first instance of the pattern and then stop searching . . . adding it will match all instances.
Those two updates should get you going.
EDIT:
Also, you may want to use match() rather than exec(). If you have a string of multiple values (e.g., "A01, B02, C03, AA18"), match() will return them all in an array, whereas, exec() will only match the first one. If it is only ever one value, then exec() will be fine (and you also wouldn't need the "global" flag).
If you want to use match(), you need to change your code order just a bit to:
var matches = sequence.match(/[a-zA-Z]+/g);
To return an array of separate letters remove +:
var matches = sequence.match(/[a-zA-Z]/g);
You're confused about what the goal of the other question was: he wanted to check that there were only letters in his string.
You need to remove the anchors ^$, who match respectively the beginning and end of the string:
[a-zA-Z]+
This will match the first of letters in your input string.
If there might be more (ie you want multiple matches in your single string), use
sequence.match(/[a-zA-Z]+/g)
This /[^a-z]/g solves the problem. Look at the example below.
function pangram(str) {
let regExp = /[^a-z]/g;
let letters = str.toLowerCase().replace(regExp, '');
document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2## %hfr efg uor7 489(*&^% knt lhtkjj ngnm!##$%^&*()_');
<h4 id="letters"></h4>
You can do this:
var r = 'AA18'.replace(/[\W\d_]/g, ''); // AA
Also can be done by String.prototype.split(regex).
'AA12BB34'.split(/(\d+)/); // ["AA", "12", "BB", "34", ""]
'AA12BB34'.split(/(\d+)/)[0]; // "AA"
Here regex divides the giving string by digits (\d+)

Javascript Regex Object Doesn't Recognize {n,m}

I'm trying to write a regular expression in JS to recognize any digit up to seven times, followed by a "-" followed by 2 digits followed by "-" followed by a single digit. This is the simple regex I have:
/\d{1,7}-\d{2}-\d/g
This should match strings like:
123-12-7
1-12-7
1234567-12-7
but not 12345678-12-1
However, the above is returning true. The regex returns true when there is any number of digit in the first group.
Does the JavaScript Regex object not support {n,m}?
Here is an example of what I am talking about.
var pattern = new RegExp(/\d{1,7}-\d{2}-\d/);
alert(pattern.test("12345678-13-1"));
http://jsfiddle.net/XTRAc/1/ live example
It matches 2345678-13-1. You need to anchor it to the beginning and end of your string:
/^\d{1,7}-\d{2}-\d$/
Note though, that (as Rocket Hazmat pointed out) you do not need to use the RegExp constructor if you use a regex literal (something without string quotes).
JSFiddle
It does support the {min,max}-syntax, but .match and .test() try to find matching substrings. You will have to include start and end anchors. Also notice that you should either use the RegExp constructor to build a regex from a string or a regex literal, but not both (see MDN: creating regexes).
/^\d{1,7}-\d{2}-\d$/
new RegExp("^\\d{1,7}-\\d{2}-\\d$") // the worse choice
You are constructing your regex incorrectly. Try this (note the anchors, which ensure the string consists of nothing but your pattern):
var pattern= /^\d{1,7}-\d{2}-\d$/;
Otherwise subsets of the existing string will match your regex.
If you need to validate entire input string, use regex pattern
/^\d{1,7}-\d{2}-\d$/
If you need to validate entire line of input string, use regex pattern
/^\d{1,7}-\d{2}-\d$/mg
If you need to find matches within input string, use regex pattern
/(?:\D|^)(\d{1,7}-\d{2}-\d)(?!\d)/g
...and use $1 as a result.
It does support the {n,m} part, the problem here is that your example matches 2345678, so you would need a way of matching the character before the first set of digits

Replacing second part of string with Javascript and replace()

I need to replace any occurrence of a sequence of integers followed by a dash and then another sequence of integers, with only the first sequence of integers. For example:
THIS IS A STRING 2387263-1111 STRING CONTINUES
Will become:
THIS IS A STRING 2387263 STRING CONTINUES
Can I use that with Javascript and replace()?
You can do:
str = str.replace(/(\d+)-\d+/,'$1');
See it
Which replaces a group of digits followed by a hyphen followed by a group of digits with the first group of digits.
If you want to replace multiple occurrences of such pattern just use the g modifier as:
str = str.replace(/(\d+)-\d+/g,'$1');
NEW ANSWER -
Yes, in your case according to me, first you need to match that whole string "2387263-1111" using a regex and then remove that part followed by '-' and then replace the result in the original string.
Check the answer from codaddict. Mine would've almost been same but his answer seems more appropriate.
OLD ANSWER: -
Why replace? Just use split and get the first value.
var str = "2387263-1111";
var output = str.split("-")[0];
User RegExp function of javascript
str = str.replace(new RegExp("-[0-9]+"), " ");
Not really a new answer, just an addition to codaddict. Don't know JScript's regex
all that well, but I asume it uses extended regular expressions (if not, forget this).
If you need validation on boundry conditions you could do something like this:
str = str.replace( /((^|\s)\d+)-\d+(?=\s|$)/g, '$1' );
That would prevent matching this type of thing:
A STRING 2387263-1111STRING CONTINUES
A STRING2387263-1111 STRING CONTINUES
A STRING2387263-1111STRING CONTINUES

Categories

Resources