replace first n occurrence of a string - javascript

I have a string var with following:
var str = getDataValue();
//str value is in this format = "aVal,bVal,cVal,dVal,eVal"
Note that the value is separated by , respectively, and the val is not fixed / hardcoded.
How do I replace only the bVal everytime?

EDIT
If you use string as the regex, escape the string to prevent malicious attacks:
RegExp.escape = function(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
new RegExp(RegExp.escape(string));
var str = "aVal,bVal,cVal,dVal,eVal";
var rgx = 'bVal';
var x = 'replacement';
var res = str.replace(rgx, x);
console.log(res);

Try this
var targetValue = 'bVal';
var replaceValue = 'yourValue';
str = str.replace(targetValue , replaceValue);

Related

JavaScript get number with comma from string

For example we have next string in javaScript
var str = "abc,de 55,5gggggg,hhhhhh 666 "
How i can get 55,5 as number?
It depends on what you can assume about your number, but for the example and a lot of cases this should work:
var str = "abc,de 55,5gggggg,hhhhhh";
var match = /\d+(,\d+)?/.exec(str);
var number;
if (match) {
number = Number(match[0].replace(',', '.'));
console.log(number);
} else console.log("didnt find anything.");
var str = "abc,de 55,5gggggg,hhhhhh"
var intRegex = /\d+((.|,)\d+)?/
var number = str.match(intRegex);
console.log(number[0]);
JS fiddle:
https://jsfiddle.net/jiteshsojitra/5vk1mxxw/
var str = "abc,de 55,5gggggg,hhhhhh"
str = str.replace(/([a-zA-Z ])/g, "").replace(/,\s*$/, "");
if (str.match(/,/g).length > 1) // if there's more than one comma
str = str.replace(',', '');
alert (str);

How can I get this result in RegEx using Javascript

If my entry is "001.1-2016", I want "001.2-2016"
If my entry is "001.8-2015", I want "001.9-2016"
If my entry is "001.12-2014", I want "001.13-2016"
If my entry is "001.123-2016", I want "001.124-2016"
I tried a regex like this:
([0-9]{3}\.)(.*)(\-[0-9]{4})
but this get all, I want only the middle.
Your regex (\[0-9\]{3}\.)(.*)(\-\[0-9\]{4}) works fine, you just need to get the second captured group result.
var arr = ["001.1-2016", "001.8-2015", "001.12-2014", "001.123-2016"];
var regex = /([0-9]{3}\.)(.*)(\-[0-9]{4})/;
arr.forEach(function(str) {
document.body.innerHTML += str.match(regex)[2] + '<br />';
});
You can use String#split and parseInt.
var value = "001.12-2014";
var num = parseInt(value.split('.')[1], 10);
var value = "001.12-2014";
var num = parseInt(value.split('.')[1], 10);
document.body.innerHTML = num;
Using Regex
var value = "001.12-2014";
var num = value.match(/.*?\.(\d+)/)[1];
var value = "001.12-2014";
var num = (value.match(/.*?\.(\d+)/) || [])[1];
document.body.innerHTML = num;
I need just add +1 in this number, eg. "001.12-2014" >>> "001.13-2014" or "001.123-2014" >>> "001.124-2014"
var arr = ["001.1-2016", "001.8-2015", "001.12-2014", "001.123-2016"];
arr = arr.map(e => e.replace(/\.(\d+)/, ($0, $1) => '.' + (1 + +$1)));
document.body.innerHTML = arr;
To increment the number by 1 you can use String#replace
document.getElementById('input').addEventListener('keyup', function() {
var value = this.value;
value = value.replace(/\.(\d+)/, function($0, $1) {
return '.' + (1 + +($1 || 0));
});
document.getElementById('output').innerHTML = value;
}, false);
<input type="text" id="input" />
<pre id="output"></pre>
The regex pattern could be
/[0-9]+\.([0-9]+)\-[0-9]+/g
if you do not concern the number format before . and after -
You can test it on here.
Try to use split method .The split() method splits a String object into an array of strings by separating the string into substrings.
<script>
function myFunction() {
var str = "001.12-2014";
var res = new Array();
res=str.split(".");
var finalres=res[1].split("-",1);
document.getElementById("demo").innerHTML = finalres;
}
</script>
Output:
this matches all 4 (find the decimal and take one or more digits that follow):
/\.(\d+)/g
# https://regex101.com/r/qG2mX7/4

How to get particular string from one big string ?

I have string
var str = "Ahora MXN$1,709.05" and wanted to get only
"MXN$1,709.05" from this.
Can someone please help me?
You can use substring or replace. With replace you are going to replace something with nothing.
replace
var str = 'Ahora MXN$1,709.05';
var sub = 'Ahora ';
var res = str.replace(sub,'');
substring
var str = 'Ahora MXN$1,709.05';
var sub = 'Ahora ';
var res = str.substring(sub.length);
JsFiddle
You can use either substring or Regex
Using substring
var str = "Ahora MXN$1,709.05";
var result = str.substring('Ahora '.length);
console.log(result);
Using Regex
var str = "Ahora MXN$1,709.05";
var myRegexp = /Ahora\s(.*?)(?:\s|$)/g;
var match = myRegexp.exec(str);
console.log(match[1]);

JavaScript get character in sting after [ and before ]

I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));

Splitting in string in JavaScript

How to split a string in JavaScript with the "," as seperator?
var splitString = yourstring.split(',');
See split
var str = "test,test1,test2";
var arrStr = str.split(',');
var arrLength = arrStr.length; //returns 3
Use split to split your string:
"foo,bar,baz".split(",") // returns ["foo","bar","baz"]
var expression = "h,e,l,l,o";
var tokens = expression.split("\,");
alert(tokens[0]);// will return h

Categories