Any javascript string function? - javascript

Some outside code is giving me a string value like..
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
now i have to save this value to the data base but putting 0 in place of null in javascript. Is there any javascript string releated function to do this conversion?

You can simply use the replace function over and over again until all instances are replaced, but make sure that all your string will ever contain is the character sequence null or a number (and obviously the delimiting comma):
var str = "null,402,2912,null"
var index = str.indexOf("null");
while(index != -1) {
str = str.replace("null", "0");
index = str.indexOf("null");
}
You need to run a for loop because the function String.replace(search, rplc) will replace only the first instance of search with rplc. So we use the indexOf method to check, in each iteration, if the required term exists or not. Another alternative (and in my opinion, a better alternative would be:
var str = "null,402,2912,null"
var parts = str.split(",");
var data = []
for(var i=0; i<parts.length; i++) {
data[data.length] = parts[i]=="null"?0:parseInt(parts[i]);
}
Basically, what we are doing is that since you will anyways be converting this to an array of numbers (I presume, and sort of hope), we first split it into individual elements and then inspect each element to see if it is null and make the conversion accordingly.

This should answer your needs:
var str = 'null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390';
str.split(",").map(function (n) { var num = Number(n); return isNaN(num) ? 0 : num; });

The simplest solution is:
var inputString = new String("null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,");
var outputString = inputString.replace("null", "0");

What I understood from your question is:
You want to replace null with 0 in a string.
You may use
string = "null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,"
string.replace(/null/g,0)
Hope it helps.

Related

regex to find specific strings in javascript

disclaimer - absolutely new to regexes....
I have a string like this:
subject=something||x-access-token=something
For this I need to extract two values. Subject and x-access-token.
As a starting point, I wanted to collect two strings: subject= and x-access-token=. For this here is what I did:
/[a-z,-]+=/g.exec(mystring)
It returns only one element subject=. I expected both of them. Where i am doing wrong?
The g modifier does not affect exec, because exec only returns the first match by specification. What you want is the match method:
mystring.match(/[a-z,-]+=/g)
No regex necessary. Write a tiny parser, it's easy.
function parseValues(str) {
var result = {};
str.split("||").forEach(function (item) {
var parts = item.split("=");
result[ parts[0] /* key */ ] = parts[1]; /* value */
});
return result;
}
usage
var obj = parseValues("subject=something||x-access-token=something-else");
// -> {subject: "something", x-access-token: "something-else"}
var subj = obj.subject;
// -> "something"
var token = obj["x-access-token"];
// -> "something-else"
Additional complications my arise when there is an escaping schema involved that allows you to have || inside a value, or when a value can contain an =.
You will hit these complications with regex approach as well, but with a parser-based approach they will be much easier to solve.
You have to execute exec twice to get 2 extracted strings.
According to MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string.
Usually, people extract all strings matching the pattern one by one with a while loop. Please execute following code in browser console to see how it works.
var regex = /[a-z,-]+=/g;
var string = "subject=something||x-access-token=something";
while(matched = regex.exec(string)) console.log(matched);
You can convert the string into a valid JSON string, then parse it to retrieve an object containing the expected data.
var str = 'subject=something||x-access-token=something';
var obj = JSON.parse('{"' + str.replace(/=/g, '":"').replace(/\|\|/g, '","') + '"}');
console.log(obj);
I don't think you need regexp here, just use the javascript builtin function "split".
var s = "subject=something1||x-access-token=something2";
var r = s.split('||'); // r now is an array: ["subject=something1", "x-access-token=something2"]
var i;
for(i=0; i<r.length; i++){
// for each array's item, split again
r[i] = r[i].split('=');
}
At the end you have a matrix like the following:
y x 0 1
0 subject something1
1 x-access-token something2
And you can access the elements using x and y:
"subject" == r[0][0]
"x-access-token" == r[1][0]
"something2" == r[1][1]
If you really want to do it with a pure regexp:
var input = 'subject=something1||x-access-token=something2'
var m = /subject=(.*)\|\|x-access-token=(.*)/.exec(input)
var subject = m[1]
var xAccessToken = m[2]
console.log(subject);
console.log(xAccessToken);
However, it would probably be cleaner to split it instead:
console.log('subject=something||x-access-token=something'
.split(/\|\|/)
.map(function(a) {
a = a.split(/=/);
return { key: a[0], val: a[1] }
}));

Javascript regex replace with different values

I'd like to know if it is possible to replace every matching pattern in the string with not one but different values each time.
Let's say I found 5 matches in a text and I want to replace first match with a string, second match with another string, third match with another and so on... is it achievable?
var synonyms = ["extremely", "exceedingly", "exceptionally", "especially", "tremendously"];
"I'm very upset, very distress, very agitated, very annoyed and very pissed".replace(/very/g, function() {
//replace 5 matches of the keyword every with 5 synonyms in the array
});
You may try to replace the matches inside a replace callback function:
var synonyms = ["extremely", "exceedingly", "exceptionally", "especially", "tremendously"];
var cnt = 0;
console.log("I'm very upset, very distress, very agitated, very annoyed and very pissed (and very anxious)".replace(/very/g, function($0) {
if (cnt === synonyms.length) cnt = 0;
return synonyms[cnt++]; //replace 5 matches of the keyword every with 5 synonyms in the array
}));
If you have more matches than there are items in the array, the cnt will make sure the array items will be used from the first one again.
A simple recursive approach. Be sure your synonyms array has enough elements to cover all matches in your string.
let synonyms = ["extremely", "exceedingly", "exceptionally"]
let yourString = "I'm very happy, very joyful, and very handsome."
let rex = /very/
function r (s, i) {
let newStr = s.replace(rex, synonyms[i])
if (newStr === s)
return s
return r(newStr, i+1)
}
r(yourString, 0)
I would caution that if your replacement would also match your regex, you need to add an additional check.
function replaceExpressionWithSynonymsInText(text, regX, synonymList) {
var
list = [];
function getSynonym() {
if (list.length <= 0) {
list = Array.from(synonymList);
}
return list.shift();
}
return text.replace(regX, getSynonym);
}
var
synonymList = ["extremely", "exceedingly", "exceptionally", "especially", "tremendously"],
textSource = "I'm very upset, very distress, very agitated, very annoyed and very pissed",
finalText = replaceExpressionWithSynonymsInText(textSource, (/very/g), synonymList);
console.log("synonymList : ", synonymList);
console.log("textSource : ", textSource);
console.log("finalText : ", finalText);
The advantages of the above approach are, firstly one does not alter the list of synonyms,
secondly working internally with an ever new copy of the provided list and shifting it,
makes additional counters obsolete and also provides the opportunity of being able to
shuffle the new copy (once it has been emptied), thus achieving a more random replacement.
Using the example you've provided, here's what I would do.
First I would set up some variables
var text = "I'm very upset, very distress, very agitated, very annoyed and very pissed";
var regex = /very/;
var synonyms = ["extremely", "exceedingly", "exceptionally", "especially", "tremendously"];
Then count the number of matches
var count = text.match(/very/g).length;
Then I would run a loop to replace the matches with the values from the array
for(var x = 0; x < count; x++) {
text = text.replace(regex, synonyms[x]);
}
You can do it with the use of Replace() function, where you use 'g' option for global matching (finds all occurrences of searched expression). For the second argument you can use a function which returns values from your predefined array.
Here is a little fiddle where you can try it out.
var str = "test test test";
var rep = ["one", "two", "three"];
var ix = 0;
var res = str.replace(/test/g, function() {
if (ix == rep.length)
ix = 0;
return rep[ix++];
});
$("#result").text(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="result">
Result...
</p>
Yes it is achievable. There may be a more efficient answer than this, but the brute force way is to double the length of your regex. i.e. Instead of searching just A, search (/A){optionalText}(/A) and then replace /1 /2 as needed. If you need help with the regex itself, provide some code for what you're searching for and someone with more rep than me can probably comment the actual regexp.

Renumber the integers inside a string in Javascript

I want to renumber the integers inside a string, that has this format (letters and int numbers): "e1b2xx4d3".
In this example, I want to get: "e1b2xx3d4";
I have written the following JS code:
var count = 0;
var matches;
var transcript = "e1b2xx4d3";
var transcript1 = transcript;
regex = /\d+/g;
while ((matches = regex.exec(transcript)) !== null) {
transcript1 = transcript1.replace(matches[0], ++count);
}
console.log(transcript1);
The idea is to replace each number in the string by its sequence number (count), but it does not work because of destructive replaces (here, we get "e1b2xx4d3", because "xx4" is replaced with "xx3", but at the next iteration by "xx4" back).
I need to do this with regex because the case that I deal with is more complex than the one shown and requires using regex.
I think that I have to do it in two passes (iterations): 1. compiling replacements and 2. applying replacements simultaneously.
By curiousity, can someone find a way to do this in one pass ?
Fiddle: http://jsfiddle.net/0frru6fr/
This is usually done with a replacing function:
n = 0
result = "e1b2xx4d3".replace(/\d+/g, function() { return ++n })
alert(result)
See docs for more info.

javascript get string before a character

I have a string that and I am trying to extract the characters before the quote.
Example is extract the 14 from 14' - €14.99
I am using the follwing code to acheive this.
$menuItem.text().match(/[^']*/)[0]
My problem is that if the string is something like €0.88 I wish to get an empty string returned. However I get back the full string of €0.88.
What I am I doing wrong with the match?
This is the what you should use to split:
string.slice(0, string.indexOf("'"));
And then to handle your non existant value edge case:
function split(str) {
var i = str.indexOf("'");
if(i > 0)
return str.slice(0, i);
else
return "";
}
Demo on JsFiddle
Nobody seems to have presented what seems to me as the safest and most obvious option that covers each of the cases the OP asked about so I thought I'd offer this:
function getCharsBefore(str, chr) {
var index = str.indexOf(chr);
if (index != -1) {
return(str.substring(0, index));
}
return("");
}
try this
str.substring(0,str.indexOf("'"));
Here is an underscore mixin in coffescript
_.mixin
substrBefore : ->
[char, str] = arguments
return "" unless char?
fn = (s)-> s.substr(0,s.indexOf(char)+1)
return fn(str) if str?
fn
or if you prefer raw javascript : http://jsfiddle.net/snrobot/XsuQd/
You can use this to build a partial like:
var beforeQuote = _.substrBefore("'");
var hasQuote = beforeQuote("14' - €0.88"); // hasQuote = "14'"
var noQoute = beforeQuote("14 €0.88"); // noQuote = ""
Or just call it directly with your string
var beforeQuote = _.substrBefore("'", "14' - €0.88"); // beforeQuote = "14'"
I purposely chose to leave the search character in the results to match its complement mixin substrAfter (here is a demo: http://jsfiddle.net/snrobot/SEAZr/ ). The later mixin was written as a utility to parse url queries. In some cases I am just using location.search which returns a string with the leading ?.
I use "split":
let string = "one-two-three";
let um = string.split('-')[0];
let dois = string.split('-')[1];
let tres = string.split('-')[2];
document.write(tres) //three

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

Categories

Resources