This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
I'm trying to remove the euro sign from my string.
Since the string looks like this €33.0000 - €37.5000, I first explode to string on the - after I try to remove the euro sign.
var string = jQuery('#amount').val();
var arr = string.split(' - ');
if(arr[0] == arr[1]){
jQuery(this).find('.last').css("display", "none");
}else{
for(var i=0; i< arr.length; i++){
arr[i].replace('€','');
console.log(arr[i]);
}
}
When I try it on my site, the euro signs aren't removed, when I get the string like this
var string = jQuery('#amount').val().replace("€", "");
Only the first euro sign is removed
.replace() replace only the fisrt occurence with a string, and replace all occurences with a RegExp:
jQuery('#amount').val().replace(/€/g, "")
Try using a regular expression with global replace flag:
"€33.0000 - €37.5000".replace(/€/g,"")
First get rid of the € (Globally), than split the string into Array parts
var noeur = str.replace(/€/g, '');
var parts = noeur.split(" - ");
The problem with your first attempt is that the replace() method returns a new string. It does not alter the one it executes on.
So it should be arr[i] = arr[i].replace('€','');
Also the replace method, by default, replaces the 1st occurrence only.
You can use the regular expression support and pass the global modifier g so that it applies to the whole string
var string = Query('#amount').val().replace(/€/g, "");
var parts = /^€([0-9.]+) - €([0-9.]+)$/.exec(jQuery('#amount').val()), val1, val2;
if (parts) {
val1 = parts[1];
val2 = parts[2];
} else {
// there is an error in your string
}
You can also tolerate spaces here and there: /^\s*€\s*([0-9.]+)\s*-\s*€\s*([0-9.]+)\s*$/
Related
This question already has answers here:
Remove trailing numbers from string js regexp
(2 answers)
Closed 3 years ago.
How would I remove _100 from the end of the string, It should be removed only at the end of the string.
For e.g
marks_old_100 should be "marks_old".
marks_100 should be "marks".
function numInString(strs) {
let newStr = ''
for (let i = 0; i < strs.length; i++) {
let noNumRegex = /\d/
let isAlphRegex = /[a-zA-Z]$/
if (isAlphRegex.test(strs[i])) {
newStr += strs[i]
}
}
return newStr
}
console.log(numInString('marks_100'))
Please check the following snippet:
const s = 'marks_old_100';
// remove any number
console.log(s.replace(/_[0-9]+$/, ''));
// remove three digit number
console.log(s.replace(/_[0-9]{3}$/, ''));
// remove _100, _150, _num
console.log(s.replace(/_(100|150|num)$/, ''));
Try:
string.replace(/_\d+$/g, "")
It makes use of regexes, and the $ matches the end of the string. .replace then replaces it with an empty string, returning the string without \d+ on the end. \d matches any digits, and + means to match more one or more.
Alternatively, if you want to match the end of a word, try:
string.replace(/_\d+\b/g, "")
which utilises \b, to match the end of a word.
This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
How can I convert a comma-separated string to an array?
(19 answers)
Closed 4 years ago.
I have some problem with my string, the variable name is accountcode. I want only part of the string. I want everything in the string which is after the first ,, excluding any extra space after the comma. For example:
accountcode = "xxxx, tes";
accountcode = "xxxx, hello";
Then I want to output like tes and hello.
I tried:
var s = 'xxxx, hello';
s = s.substring(0, s.indexOf(','));
document.write(s);
Just use split with trim.
var accountcode = "xxxx, tes";
var result= accountcode.split(',')[1].trim();
console.log(result);
You can use String.prototype.split():
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
You can use length property of the generated array as the last index to access the string item. Finally trim() the string:
var s = 'xxxx, hello';
s = s.split(',');
s = s[s.length - 1].trim();
document.write(s);
You can use string.lastIndexOf() to pull the last word out without making a new array:
let accountcode = "xxxx, hello";
let lastCommaIndex = accountcode.lastIndexOf(',')
let word = accountcode.slice(lastCommaIndex+1).trim()
console.log(word)
You can split the String on the comma.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1]);
If you don't want any leading or trailing spaces, use trim.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1].trim());
accountcode = "xxxx, hello";
let macthed=accountcode.match(/\w+$/)
if(matched){
document.write(matched[0])
}
here \w+ means any one or more charecter
and $ meand end of string
so \w+$ means get all the character upto end of the sting
so here ' ' space is not a whole character so it started after space upto $
the if statement is required because if no match found than macthed will be null , and it found it will be an array and first element will be your match
This question already has answers here:
Javascript and regex: split string and keep the separator
(11 answers)
Closed 6 years ago.
I have the following string
str = "11122+3434"
I want to split it into ["11122", "+", "3434"]. There can be following delimiters +, -, /, *
I have tried the following
strArr = str.split(/[+,-,*,/]/g)
But I get
strArr = [11122, 3434]
Delimiters are things that separate data. So the .split() method is designed to remove delimiters since delimiters are not data so they are not important at all.
In your case, the thing between two values is also data. So it's not a delimiter, it's an operator (in fact, that's what it's called in mathematics).
For this you want to parse the data instead of splitting the data. The best thing for that is therefore regexp:
var result = str.match(/(\d+)([+,-,*,/])(\d+)/);
returns an array:
["11122+3434", "11122", "+", "3434"]
So your values would be result[1], result[2] and result[3].
This should help...
str = '11122+3434+12323*56767'
strArr = str.replace(/[+,-,*,/]/g, ' $& ').split(/ /g)
console.log(strArr)
Hmm, one way is to add a space as delimiter first.
// yes,it will be better to use regex for this too
str = str.replace("+", " + ");
Then split em
strArr = str.split(" ");
and it will return your array
["11122", "+", "3434"]
in bracket +-* need escape, so
strArr = str.split(/[\+\-\*/]/g)
var str = "11122+77-3434";
function getExpression(str) {
var temp = str.split('');
var part = '';
var result = []
for (var i = 0; i < temp.length; i++) {
if (temp[i].match(/\d/) && part.match(/\d/g)) {
part += temp[i];
} else {
result.push(part);
part = temp[i]
}
if (i === temp.length - 1) { //last item
result.push(part);
part = '';
}
}
return result;
}
console.log(getExpression(str))
This question already has answers here:
Create RegExps on the fly using string variables
(6 answers)
Closed 8 years ago.
I have an array of alphabets in the form of letter strings
alpha = ['a','b', etc..];
I'm counting up numbers of each letter in a word like so
for (j=0;j<alpha.length;j++){
num = word.match(/alpha[j]/g).length;}
Problem is that, for example, alpha[0] is 'a', not a and match regex only recognizes a .
How can I convert from 'a' to a so that match recognizes it?
To clarify
"ara".match(/a/g) returns ["a","a"] while "ara".match(/'a'/g) returns null.
You can construct a RegExp from a string with the RegExp constructor as described here.
for (j=0;j<alpha.length;j++){
var matches = word.match(new RegExp(alpha[j], "g"));
if (matches) {
num = matches.length;
// other code here to process the match
}
}
This assumes that none of the characters in the alpha array will be special characters in a regular expression because if they are, you will have to escape them so they are treated as normal characters.
As jfriend00 suggests, you can use the RegExp constructor like:
var re, num, matches;
for (j=0; j<alpha.length; j++){
re = new RegExp(alpha[j],'g');
matches = word.match(re);
num = matches? matches.length : 0;
}
Note that another way (shorter, faster, simpler) is:
var num = word.split('a').length - 1; // 'ara' -> 2
This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
I know there are methods to remove characters from the beginning and from the end of a string in Javascript. What I need is trim a string in such a way that only the last 4 characters remain.
For eg:
ELEPHANT -> HANT
1234567 -> 4567
String.prototype.slice will work
var str = "ELEPHANT";
console.log(str.slice(-4));
//=> HANT
For, numbers, you will have to convert to strings first
var str = (1234567).toString();
console.log(str.slice(-4));
//=> 4567
FYI .slice returns a new string, so if you want to update the value of str, you would have to
str = str.slice(-4);
Use substr method of javascript:
var str="Elephant";
var n=str.substr(-4);
alert(n);
You can use slice to do this
string.slice(start,end)
lets assume you use jQuery + javascript as well.
Lets have a label in the HTML page with id="lblTest".
<script type="text/javascript">
function myFunc() {
val lblTest = $("[id*=lblTest]");
if (lblTest) {
var str = lblTest.text();
// this is your needed functionality
alert(str.substring(str.length-4, str.length));
} else {
alert('does not exist');
}
}
</script>
Edit: so the core part is -
var str = "myString";
var output = str.substring(str.length-4, str.length);