Add to current string using javascript - javascript

I would like to add to the current string using javascript. Currently, It is working fine but I am doing it in a very dirty way currently. I am basically replacing the WHOLE string instead of just adding to it. Is there a way that I can just add a comma and continue my string?
JS:
var mystring = "'bootstrap'"
console.log(mystring.replace(/bootstrap/g , "'bootstrap', 'bootstrap2', 'bootstrap3'"));
JSFiddle

You can add to the end of a string by using the +=operator. See the docs regarding string operators.
var mystring = "'bootstrap'"
mystring += ", 'bootstrap2'";
mystring += ", 'bootstrap3'";
console.log(mystring);

You can concatenate( + operator ) instead of replace if you just want the second string to get appended to the first string.
var mystring = "'bootstrap'"
var newString = mystring +", "+ "'bootstrap', 'bootstrap2', 'bootstrap3'";
console.log( newString );

What about:
mystring += "'bootstrap2',";
or
var arr = ["str1", "str2", "str3"];
var mystring = arr.map((e)=>{return "'"+e+"'";}).join(",")
Array.map function used to wrap each string with single quates, than you Array.join - used to put "," between members

You can concat strings with the + operator:
var mystring = "'bootstrap'" + ",";
console.log(mystring);

Use an array and the join method.
var arr = [];
var myString = "bootstrap";
arr.push(myString);
arr.push(myString);
arr.push("other string");
arr.push("bootstrap");
// combine them with a comma or something else
console.log(arr.join(', '));

It is not suggested, but if you want to keep symbols and not care about order, and want to only add to a string beginning with 'bootstrap':
myString = "'bootstrap'";
console.log(myString.replace(/^(?='(bootstrap)')/, "'$12', '$13', "));
or you can just use capture group to keep it short
mystring.replace(/'(bootstrap)'/, "'$1', '$12', '$13'")

Related

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

Replace strings from left until the first occuring string in Javascript

I am trying to figure out how to replace example:
sw1_code1_number1_jpg --> code1_number1_jpg
hon2_noncode_number2_jpg --> noncode_number2_jpg
ccc3_etccode_number3_jpg --> etccode_number3_jpg
ddd4_varcode_number4_jpg --> varcode_number4_jpg
So the results are all string after the first _
If it doesn't find any _ then do nothing.
I know how to find and replace strings, str.replace, indexof, lastindexof but dont know how remove up to the first found occurrence.
Thank You
Use the replace method with a regular expression:
"sw1_code1_number1_jpg".replace(/^.*?_/, "");
You could split your string and get a slice
var str = 'sw1_code1_number1_jpg';
var finalStr = str.split('_').slice(1).join('_') || str;
If your original string does not contain an underscore, then it returns the original string.
UPDATE A simpler one with slice (still works with strings not containing underscores)
var str = 'sw1_code1_number1_jpg';
var finalStr = str.slice(str.indexOf('_') + 1);
This one works in all cases because when no underscore is found, -1 is returned and as we add 1 to the index we call str.slice(0) which is equal to str.
There are several approaches you can take:
var str = 'sw1_code1_number1_jpg';
var arr = str.split('_');
arr.shift();
var newSfr = arr.join('_');
Or you could use slice or replace:
var str = 'sw1_code1_number1_jpg';
var newStr = str.slice(str.indexOf('_')+1);
Or
var newStr = 'sw1_code1_number1_jpg'.replace(/^[^_]+_/,'');

How to use Javascript slice to extract first and last letter of a string?

How to use JavaScript slice to extract the first and last letter of a string?
Eg: "Hello World"
I need the result as "dH".
Following is my jsfiddle :
http://jsfiddle.net/vSAs8/
Here's the cleanest solution :
var output = input.slice(-1)+input[0];
If you want more slice, there's also
var output = input.slice(-1)+input.slice(0,1);
And here are alternate fun (and less efficient) solutions :
var output = input.replace(/^(.).*(.)$/,'$2$1');
or
var output = input.match(/^.|.$/g).reverse().join('');
Substr works as well:
alert(test.substr(-1,1) + test.substr(0,1));
a.charAt(a.length-1) + a.charAt(0)
var str = " Virat Kohali "
var get_string_label = function(str){
str = str.split(" ");
str = str.filter(res=>res.length>0);
str = str.map(function(res){
return res[0].toUpperCase();
});
str = str.join("");
return str;
};
console.log(get_string_label(str));
str.split(" "); method splits a String object into an array of strings by separating the string into substrings, where it will find space in string.
then str.filter(res=>res.length>0) will filter out string having zero length (for "virat kohali" string you will get empty sub-string)
after that using map function you can fetch your first letter

Convert string with commas to array

How can I convert a string to a JavaScript array?
Look at the code:
var string = "0,1";
var array = [string];
alert(array[0]);
In this case alert shows 0,1. If it where an array, it would show 0. And if alert(array[1]) is called, it should pop-up 1
Is there any chance to convert such string into a JavaScript array?
For simple array members like that, you can use JSON.parse.
var array = JSON.parse("[" + string + "]");
This gives you an Array of numbers.
[0, 1]
If you use .split(), you'll end up with an Array of strings.
["0", "1"]
Just be aware that JSON.parse will limit you to the supported data types. If you need values like undefined or functions, you'd need to use eval(), or a JavaScript parser.
If you want to use .split(), but you also want an Array of Numbers, you could use Array.prototype.map, though you'd need to shim it for IE8 and lower or just write a traditional loop.
var array = string.split(",").map(Number);
Split it on the , character;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
This is easily achieved in ES6;
You can convert strings to Arrays with Array.from('string');
Array.from("01")
will console.log
['0', '1']
Which is exactly what you're looking for.
If the string is already in list format, you can use the JSON.parse:
var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);
Convert all type of strings
var array = (new Function("return [" + str+ "];")());
var string = "0,1";
var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var stringArray = (new Function("return [" + string+ "];")());
var objectStringArray = (new Function("return [" + objectstring+ "];")());
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/
Result in console
Some practice doesnt support object strings
- JSON.parse("[" + string + "]"); // throw error
- string.split(",")
// unexpected result
["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", " {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"", " CatGroupName:"Leather"", " Gender:"child"}"]
For simple array members like that, you can use JSON.parse.
var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";
var array = JSON.parse("[" + listValues + "]");
This gives you an Array of numbers.
now you variable value is like array.length=1
Value output
array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes
You can use split
Reference:
http://www.w3schools.com/jsref/jsref_split.asp
"0,1".split(',')
Another option using the ES6 is using Spread syntax.
var convertedArray = [..."01234"];
var stringToConvert = "012";
var convertedArray = [...stringToConvert];
console.log(convertedArray);
use the built-in map function with an anonymous function, like so:
string.split(',').map(function(n) {return Number(n);});
[edit] here's how you would use it
var string = "0,1";
var array = string.split(',').map(function(n) {
return Number(n);
});
alert( array[0] );
How to Convert Comma Separated String into an Array in JavaScript?
var string = 'hello, world, test, test2, rummy, words';
var arr = string.split(', '); // split string on comma space
console.log( arr );
//Output
["hello", "world", "test", "test2", "rummy", "words"]
For More Examples of convert string to array in javascript using the below ways:
Split() – No Separator:
Split() – Empty String Separator:
Split() – Separator at Beginning/End:
Regular Expression Separator:
Capturing Parentheses:
Split() with Limit Argument
check out this link
==> https://www.tutsmake.com/javascript-convert-string-to-array-javascript/
You can use javascript Spread Syntax to convert string to an array. In the solution below, I remove the comma then convert the string to an array.
var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])
I remove the characters '[',']' and do an split with ','
let array = stringObject.replace('[','').replace(']','').split(",").map(String);
More "Try it Yourself" examples below.
Definition and Usage
The split() method is used to split a string into an array of substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is split between each character.
Note: The split() method does not change the original string.
var res = str.split(",");
Regexp
As more powerful alternative to split, you can use match
"0,1".match(/\d+/g)
let a = "0,1".match(/\d+/g)
console.log(a);
Split (",") can convert Strings with commas into a String array, here is my code snippet.
var input ='Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, Android Wear API'
var output = input.split(",");
console.log(output);
["Hybrid App", " Phone-Gap", " Apache Cordova", " HTML5", "
JavaScript", " BootStrap", " JQuery", " CSS3", " Android Wear API"]
var i = "[{a:1,b:2}]",
j = i.replace(/([a-zA-Z0-9]+?):/g, '"$1":').replace(/'/g,'"'),
k = JSON.parse(j);
console.log(k)
// => declaring regular expression
[a-zA-Z0-9] => match all a-z, A-Z, 0-9
(): => group all matched elements
$1 => replacement string refers to the first match group in the regex.
g => global flag
Why don't you do replace , comma and split('') the string like this which will result into ['0', '1'], furthermore, you could wrap the result into parseInt() to transform element into integer type.
it('convert string to array', function () {
expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
});
Example using Array.filter:
var str = 'a,b,hi,ma,n,yu';
var strArr = Array.prototype.filter.call(str, eachChar => eachChar !== ',');

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

I want to use str_replace or its similar alternative to replace some text in JavaScript.
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);
should give
this is some sample text that i dont want to replace
If you are going to regex, what are the performance implications in
comparison to the built in replacement methods.
You would use the replace method:
text = text.replace('old', 'new');
The first argument is what you're looking for, obviously. It can also accept regular expressions.
Just remember that it does not change the original string. It only returns the new value.
More simply:
city_name=city_name.replace(/ /gi,'_');
Replaces all spaces with '_'!
All these methods don't modify original value, returns new strings.
var city_name = 'Some text with spaces';
Replaces 1st space with _
city_name.replace(' ', '_'); // Returns: "Some_text with spaces" (replaced only 1st match)
Replaces all spaces with _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/
city_name.replace(/ /gi,'_'); // Returns: Some_text_with_spaces
Replaces all spaces with _ without regex. Functional way.
city_name.split(' ').join('_'); // Returns: Some_text_with_spaces
You should write something like that :
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
The code that others are giving you only replace one occurrence, while using regular expressions replaces them all (like #sorgit said). To replace all the "want" with "not want", us this code:
var text = "this is some sample text that i want to replace";
var new_text = text.replace(/want/g, "dont want");
document.write(new_text);
The variable "new_text" will result in being "this is some sample text that i dont want to replace".
To get a quick guide to regular expressions, go here:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
To learn more about str.replace(), go here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
Good luck!
that function replaces only one occurrence.. if you need to replace
multiple occurrences you should try this function:
http://phpjs.org/functions/str_replace:527
Not necessarily.
see the Hans Kesting answer:
city_name = city_name.replace(/ /gi,'_');
Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:
Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.
For a simple test run on the JS perf page, I've documented some of the results:
<script>
// Setup
var startString = "xxxxxxxxxabcxxxxxxabcxx";
var endStringRegEx = undefined;
var endStringString = undefined;
var endStringRegExNewStr = undefined;
var endStringRegExNew = undefined;
var endStringStoredRegEx = undefined;
var re = new RegExp("abc", "g");
</script>
<script>
// Tests
endStringRegEx = startString.replace(/abc/g, "def") // Regex
endStringString = startString.replace("abc", "def", "g") // String
endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
endStringStoredRegEx = startString.replace(re, "def") // saved regex
</script>
The results for Chrome 68 are as follows:
String replace: 9,936,093 operations/sec
Saved regex: 5,725,506 operations/sec
Regex: 5,529,504 operations/sec
New Regex String: 3,571,180 operations/sec
New Regex: 3,224,919 operations/sec
From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace only replaces the first instance of the matched character. Its only possible to replace all instances with //g. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); or worse while (name.includes(' ')) { name = name.replace(' ', '_') }
var new_text = text.replace("want", "dont want");
hm.. Did you check replace() ?
Your code will look like this
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
JavaScript has replace() method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example of replace() method having both string arguments is shown below.
var text = 'one, two, three, one, five, one';
var new_text = text.replace('one', 'ten');
console.log(new_text) //ten, two, three, one, five, one
Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a g (global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences of one in the above example.
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, 'ten');
console.log(new_text) //ten, two, three, ten, five, ten
Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag i which makes the pattern case-insensitive. In that case the above regular expression will be /one/gi. Notice the i flag added here.
If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, function(match, pos, text){
return 'ten';
});
console.log(new_text) //ten, two, three, ten, five, ten
You can have more control over the replacement text using a function as the second argument.
In JavaScript, you call the replace method on the String object, e.g. "this is some sample text that i want to replace".replace("want", "dont want"), which will return the replaced string.
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched
You can use
text.replace('old', 'new')
And to change multiple values in one string at once, for example to change # to string v and _ to string w:
text.replace(/#|_/g,function(match) {return (match=="#")? v: w;});
There are already multiple answers using str.replace() (which is fair enough for this question) and regex but you can use combination of str.split() and join() together which is faster than str.replace() and regex.
Below is working example:
var text = "this is some sample text that i want to replace";
console.log(text.split("want").join("dont want"));
If you really want a equivalent to PHP's str_replace you can use Locutus. PHP's version of str_replace support more option then what the JavaScript String.prototype.replace supports.
For example tags:
//PHP
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
//JS with Locutus
var $bodytag = str_replace(['{body}', 'black', '<body text='{body}'>')
or array's
//PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
//JS with Locutus
var $vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
var $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
Also this doesn't use regex instead it uses for loops. If you not want to use regex but want simple string replace you can use something like this ( based on Locutus )
function str_replace (search, replace, subject) {
var i = 0
var j = 0
var temp = ''
var repl = ''
var sl = 0
var fl = 0
var f = [].concat(search)
var r = [].concat(replace)
var s = subject
s = [].concat(s)
for (i = 0, sl = s.length; i < sl; i++) {
if (s[i] === '') {
continue
}
for (j = 0, fl = f.length; j < fl; j++) {
temp = s[i] + ''
repl = r[0]
s[i] = (temp).split(f[j]).join(repl)
if (typeof countObj !== 'undefined') {
countObj.value += ((temp.split(f[j])).length - 1)
}
}
}
return s[0]
}
var text = "this is some sample text that i want to replace";
var new_text = str_replace ("want", "dont want", text)
document.write(new_text)
for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js
You have the following options:
Replace the first occurrence
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace('want', 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"
console.log(new_text)
Replace all occurrences - case sensitive
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/g, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well
console.log(new_text)
Replace all occurrences - case insensitive
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/gi, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i dont want to replace as well
console.log(new_text)
More info -> here
In Javascript, replace function available to replace sub-string from given string with new one.
Use:
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
console.log(new_text);
You can even use regular expression with this function. For example, if want to replace all occurrences of , with ..
var text = "123,123,123";
var new_text = text.replace(/,/g, ".");
console.log(new_text);
Here g modifier used to match globally all available matches.
Method to replace substring in a sentence using React:
const replace_in_javascript = (oldSubStr, newSubStr, sentence) => {
let newStr = "";
let i = 0;
sentence.split(" ").forEach(obj => {
if (obj.toUpperCase() === oldSubStr.toUpperCase()) {
newStr = i === 0 ? newSubStr : newStr + " " + newSubStr;
i = i + 1;
} else {
newStr = i === 0 ? obj : newStr + " " + obj;
i = i + 1;
}
});
return newStr;
};
RunMethodHere
If you don't want to use regex then you can use this function which will replace all in a string
Source Code:
function ReplaceAll(mystring, search_word, replace_with)
{
while (mystring.includes(search_word))
{
mystring = mystring.replace(search_word, replace_with);
}
return mystring;
}
How to use:
var mystring = ReplaceAll("Test Test", "Test", "Hello");
Use JS String.prototype.replace first argument should be Regex pattern or String and Second argument should be a String or function.
str.replace(regexp|substr, newSubStr|function);
Ex:
var str = 'this is some sample text that i want to replace';
var newstr = str.replace(/want/i, "dont't want");
document.write(newstr); // this is some sample text that i don't want to replace
ES2021 / ES12
String.prototype.replaceAll()
is trying to bring the full replacement option even when the input pattern is a string.
const str = "Backbencher sits at the Back";
const newStr = str.replaceAll("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Front"
1- String.prototype.replace()
We can do a full **replacement** only if we supply the pattern as a regular expression.
const str = "Backbencher sits at the Back";
const newStr = str.replace(/Back/g, "Front");
console.log(newStr); // "Frontbencher sits at the Front"
If the input pattern is a string, replace() method only replaces the first occurrence.
const str = "Backbencher sits at the Back";
const newStr = str.replace("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Back"
2- You can use split and join
const str = "Backbencher sits at the Back";
const newStr = str.split("Back").join("Front");
console.log(newStr); // "Frontbencher sits at the Front"
function str_replace($old, $new, $text)
{
return ($text+"").split($old).join($new);
}
You do not need additional libraries.
In ECMAScript 2021, you can use replaceAll can be used.
const str = "string1 string1 string1"
const newStr = str.replaceAll("string1", "string2");
console.log(newStr)
// "string2 string2 string2"
simplest form as below
if you need to replace only first occurrence
var newString = oldStr.replace('want', 'dont want');
if you want ot repalce all occurenace
var newString = oldStr.replace(want/g, 'dont want');
Added a method replace_in_javascript which will satisfy your requirement. Also found that you are writing a string "new_text" in document.write() which is supposed to refer to a variable new_text.
let replace_in_javascript= (replaceble, replaceTo, text) => {
return text.replace(replaceble, replaceTo)
}
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);

Categories

Resources