I have the string:
"A1111A2222A3333A4444"
how do I get the string:
"A1111"
I need to be able to get it by specifying the number of 'A' chars from the end and removing this portion from the total string.
EDIT:
I have a large string separated by the char 'A', for example:
"A11A22A33A44A55A66A77A88A99"
What I need is a function that will give me the substring from 0 to the index of n 'A' chars away. For example, getSubstring(3) would return:
"A11A22A33A44A55A66"
You can:
split the string using the character as the separator
Use slice to get a subarray with all items except the last n items
join back that subarray
function getSubstring(str, ch, n) {
return str.split(ch).slice(0, -n).join(ch);
}
getSubstring("A1111A2222A3333A4444", "A", 3); // "A1111"
getSubstring("A11A22A33A44A55A66A77A88A99", "A", 3); // "A11A22A33A44A55A66"
Given
var str = "A1111A2222A3333A4444";
var pattern = /A1*4/;
search() will tell you at what index the match was found
str.search(pattern)
match() will return 'A1111'. (match accually returns an array with [0] being the string that was searched and [1] being the matched part of the string.
str.match(pattern)[1];
Related
I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)
I have the following Javascript
function myFunction() {
var str = "depth10 shown";
var depth= str.match(/^depth[\d+$]/);
console.log(depth);
}
My function is trying to find if depth* is present in the string, where * is always numeric (ex: depth0, depth1, depth100) and return the numeric value in it. In the example above, depth is always returning only one digit instead of all digits. Can anyone explain why?
You're improperly utilizing a character class, you want to use a capturing group instead:
var str = 'depth10 shown or depth100 and depth1'
var re = /depth(\d+)/gi,
matches = [];
while (m = re.exec(str)) {
matches.push(m[1]);
}
console.log(matches) //=> [ '10', '100', '1' ]
Note: If you will have more than 1 "depth*" substrings in your string, you'll want to use the exec() method in a loop pushing the match result of the captured group to the results array.
Otherwise, you can use the match method here:
var r = 'depth10 shown'.match(/depth(\d+)/)
if (r)
console.log(r[1]); //=> "10"
$ Matches end of input. ie. /t$/ does not match the 't' in "eater", but does match it in "eat".
^ Matches beginning of input. ie, /^A/ does not match the 'A' in "an A", but does match the 'A' in "An E".
Try:
var str = "depth10 shown".match(/depth\d+/gi);
console.log(str[0])
I am trying to remove some spaces from a few dynamically generated strings. Which space I remove depends on the length of the string. The strings change all the time so in order to know how many spaces there are, I iterate over the string and increment a variable every time the iteration encounters a space. I can already remove all of a specific type of character with str.replace(' ',''); where 'str' is the name of my string, but I only need to remove a specific occurrence of a space, not all the spaces. So let's say my string is
var str = "Hello, this is a test.";
How can I remove ONLY the space after the word "is"? (Assuming that the next string will be different so I can't just write str.replace('is ','is'); because the word "is" might not be in the next string).
I checked documentation on .replace, but there are no other parameters that it accepts so I can't tell it just to replace the nth instance of a space.
If you want to go by indexes of the spaces:
var str = 'Hello, this is a test.';
function replace(str, indexes){
return str.split(' ').reduce(function(prev, curr, i){
var separator = ~indexes.indexOf(i) ? '' : ' ';
return prev + separator + curr;
});
}
console.log(replace(str, [2,3]));
http://jsfiddle.net/96Lvpcew/1/
As it is easy for you to get the index of the space (as you are iterating over the string) , you can create a new string without the space by doing:
str = str.substr(0, index)+ str.substr(index);
where index is the index of the space you want to remove.
I came up with this for unknown indices
function removeNthSpace(str, n) {
var spacelessArray = str.split(' ');
return spacelessArray
.slice(0, n - 1) // left prefix part may be '', saves spaces
.concat([spacelessArray.slice(n - 1, n + 1).join('')]) // middle part: the one without the space
.concat(spacelessArray.slice(n + 1)).join(' '); // right part, saves spaces
}
Do you know which space you want to remove because of word count or chars count?
If char count, you can Rafaels Cardoso's answer,
If word count you can split them with space and join however you want:
var wordArray = str.split(" ");
var newStr = "";
wordIndex = 3; // or whatever you want
for (i; i<wordArray.length; i++) {
newStr+=wordArray[i];
if (i!=wordIndex) {
newStr+=' ';
}
}
I think your best bet is to split the string into an array based on placement of spaces in the string, splice off the space you don't want, and rejoin the array into a string.
Check this out:
var x = "Hello, this is a test.";
var n = 3; // we want to remove the third space
var arr = x.split(/([ ])/); // copy to an array based on space placement
// arr: ["Hello,"," ","this"," ","is"," ","a"," ","test."]
arr.splice(n*2-1,1); // Remove the third space
x = arr.join("");
alert(x); // "Hello, this isa test."
Further Notes
The first thing to note is that str.replace(' ',''); will actually only replace the first instance of a space character. String.replace() also accepts a regular expression as the first parameter, which you'll want to use for more complex replacements.
To actually replace all spaces in the string, you could do str.replace(/ /g,""); and to replace all whitespace (including spaces, tabs, and newlines), you could do str.replace(/\s/g,"");
To fiddle around with different regular expressions and see what they mean, I recommend using http://www.regexr.com
A lot of the functions on the JavaScript String object that seem to take strings as parameters can also take regular expressions, including .split() and .search().
I have a strings "add_dinner", "add_meeting", "add_fuel_surcharge" and I want to get characters that are preceded by "add_" (dinner, meeting, fuel_surcharge).
[^a][^d]{2}[^_]\w+
I have tried this one, but it only works for "add_dinner"
[^add_]\w+
This one works for "add_fuel_surcharge", but takes "inner" from "add_dinner"
Help me to understand please.
Use capturing groups:
/^add_(\w+)$/
Check the returned array to see the result.
Since JavaScript doesn't support lookbehind assertions, you need to use a capturing group:
var myregexp = /add_(\w+)/;
var match = myregexp.exec(subject);
if (match != null) {
result = match[1];
}
[^add_] is a character class that matches a single character except a, d or _. When applied to add_dinner, the first character it matches is i, and \w+ then matches nner.
The [^...] construct matches any single character except the ones listed. So [^add_] matches any single character other than "a", "d" or "_".
If you want to retrieve the bit after the _ you can do this:
/add_(\w+_)/
Where the parentheses "capture" the part of the expression inside. So to get the actual text from a string:
var s = "add_meeting";
var result = s.match(/add_(\w+)/)[1];
This assumes the string will match such that you can directly get the second element in the returned array that will be the "meeting" part that matched (\w+).
If there's a possibility that you'll be testing a string that won't match you need to test that the result of match() is not null.
(Or, possibly easier to understand: result = "add_meeting".split("_")[1];)
You can filter _ string by JavaScript for loop ,
var str = ['add_dinner', 'add_meeting', 'add_fuel_surcharge'];
var filterString = [];
for(var i = 0; i < str.length; i ++){
if(str[i].indexOf("_")>-1){
filterString.push(str[i].substring(str[i].indexOf("_") + 1, str[i].length));
}
}
alert(filterString.join(", "));
What I'd like to achieve is splitting a string like this, i.e. the delimiters are the indexes where the character before that index is different from the character after that index:
"AAABBCCCCDEEE" -> ["AAA", "BB", "CCCC", "D", "EEE"]
I've been trying to make up a concise solution, but I ended up with this rather verbose code: http://jsfiddle.net/b39aM/1/.
var arr = [], // output
text = "AAABBCCCCDEEE", // input
current;
for(var i = 0; i < text.length; i++) {
var char = text[i];
if(char !== current) { // new letter
arr.push(char); // create new array element
current = char; // update current
} else { // current letter continued
arr[arr.length - 1] += char; // append letter to last element
}
}
It's naive and I don't like it:
I'm manually iterating over each character, and I'm appending to the array character by character
It's a little too long for the simple thing I want to achieve
I was thinking of using a regexp but I'm not sure what the regexp should be. Is it possible to define a regexp that means "one character and a different character following"?
Or more generally, is there a more elegant solution for achieving this splitting method?
Yes, you can use a regular expression:
"AAABBCCCCDEEE".match(/(.)\1*/g)
Here . will match any character and \1* will match any following characters that are the same as the formerly matched one. And with a global match you’ll get all matching sequences.