Finding a substring and inserting another string - javascript

Suppose I have string variable such as:
var a = "xxxxxxxxhelloxxxxxxxx";
or:
var a = "xxxxhelloxxxx";
I want to insert "world" after "hello".
I can't use substr() because the position is not known ahead of time. How can I do this in JavaScript or jQuery?

var a = "xxxxhelloxxxxhelloxxxx";
a = a.replace(/hello/g,"hello world"); // if you want all the "hello"'s in the string to be replaced
document.getElementById("regex").textContent = a;
a = "xxxxhelloxxxxhelloxxxx";
a = a.replace("hello","hello world"); // if you want only the first occurrence of "hello" to be replaced
document.getElementById("string").textContent = a;
<p>With regex: <strong id="regex"></strong></p>
<p>With string: <strong id="string"></strong></p>

This will replace the first occurrence
a = a.replace("hello", "helloworld");
If you need to replace all of the occurrences, you'll need a regular expression. (The g flag at the end means "global", so it will find all occurences.)
a = a.replace(/hello/g, "helloworld");

This will replace the first occurance:
a = a.replace("hello", "hello world");
If you need to replace all occurances, you use a regular expression for the match, and use the global (g) flag:
a = a.replace(/hello/g, "hello world");

Here are two ways to avoid repeating the pattern:
a_new = a.replace(/hello/, '$& world'); // "xxxxxxxxhello worldxxxxxxxx"
$& represents the substring that matched the whole pattern. It is a special code for use in the replacement string.
a_new = a.replace(/hello/, function (match) {
return match + ' world';
});
A replacer function is passed the same substring that matched the whole pattern.

var find = "hello";
var a = "xxxxxxxxxxxxxhelloxxxxxxxxxxxxxxxx";
var i = a.indexOf(find);
var result = a.substr(0, i+find.length) + "world" + a.substr(i+find.length);
alert(result); //xxxxxxxxxxxxxhelloworldxxxxxxxxxxxxxxxx
Maybe.

You can use replace, would be much easier than indexOf
var newstring = a.replace("hello", "hello world");

Related

How to remove part of string that is in parentheses?

I have a string from which I want to remove the last parentheses "(bob)". So far I use this code to return the value within these parentheses:
const str = "Hello my name is (john) (doe) (bob)";
const result = str.split('(').pop().split(')')[0];
console.log(result);
How would I be able to return the string without these last parentheses?
Source: How to remove the last word in a string using JavaScript
Possibly not the cleanest solution, but if you always want to remove the text behind last parentheses, it will work.
var str = "Hello my name is (john) (doe) (bob)";
var lastIndex = str.lastIndexOf("(");
str = str.substring(0, lastIndex);
console.log(str);
You can match the last occurrence of the parentthesis, and replace with capture group 1 that contains all that comea before it:
^(.*)\([^()]*\)
Regex demo
const str = 'Hello my name is (john) (doe) (bob)';
const lastIdxS = str.lastIndexOf('(');
console.log(str.slice(0, lastIdxS).trim());

How to get substring from string after last seen to specific characer in javascript?

I want to get substring from string at last index match space and put it into another string :
for example
if I have : var string1="hello any body from me";
in string1 I have 4 spaces and I want to get the word after last spaces in string1 so here I want to get the word "me" ...
I don't know number of spaces in string1 ... so How I can get substring from string after last seen to specific characer like space ?
You could try something like this using the split method, where input is your string:
var splitted = input.split(' ');
var s = splitted[splitted.length-1];
var splitted = "hello any body from me".split(' ');
var s = splitted[splitted.length-1];
console.log(s);
Use split to make it an array and get the last element:
var arr = st.split(" "); // where string1 is st
var result = arr[arr.length-1];
console.log(result);
Or just :
var string1 = "hello any body from me";
var result = string1.split(" ").reverse()[0];
console.log(result); // me
Thank's to reverse method
I'd use a regular expression to avoid the array overhead:
var string1 = "hello any body from me";
var matches = /\s(\S*)$/.exec(string1);
if (matches)
console.log(matches[1]);
You can use split method to split the string by a given separator, " " in this case, and then get the final substring of the returned array.
This is a good method if you want to use other parts of the string and it is also easily readable:
// setup your string
var string1 = "hello any body from me";
// split your string into an array of substrings with the " " separator
var splitString = string1.split(" ");
// get the last substring from the array
var lastSubstr = splitString[splitString.length - 1];
// this will log "me"
console.log(lastSubstr);
// ...
// oh i now actually also need the first part of the string
// i still have my splitString variable so i can use this again!
// this will log "hello"
console.log(splitString[0]);
This is a good method without the need for the rest of the substrings if you prefer to write quick and dirty:
// setup your string
var string1 = "hello any body from me";
// split your string into an array of substrings with the " " separator, reverse it, and then select the first substring
var lastSubstr = string1.split(" ").reverse()[0];
// this will log "me"
console.log(lastSubstr);

Replace a substring with javascript

Need to replace a substring in URL (technically just a string) with javascript.
The string like
http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE
or
http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest
means, the word to replace can be either at the most end of the URL or in the middle of it.
I am trying to cover these with the following:
var newWord = NEW_SEARCH_TERM;
var str = 'http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest';
var regex = /^\S+SearchableText=(.*)&?\S*$/;
str = str.replace(regex, newWord);
But no matter what I do I get str = NEW_SEARCH_TERM. Moreover the regular expression when I try it in RegExhibit, selects the word to replace and everything that follows it that is not what I want.
How can I write a universal expression to cover both cases and make the correct string be saved in the variable?
str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)
The \S+ and \S* in your regex match all non-whitespace characters.
You probably want to remove them and the anchors.
http://jsfiddle.net/mplungjan/ZGbsY/
ClyFish did it while I was fiddling
var url1="http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE";
var url2 ="http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest"
var newWord = "foo";
function replaceSearch(str,newWord) {
var regex = /SearchableText=[^&]*/;
return str.replace(regex, "SearchableText="+newWord);
}
document.write(replaceSearch(url1,newWord))
document.write('<hr>');
document.write(replaceSearch(url2,newWord))

Javascript replace regex wildcard

I have a string which I need to run a replace.
string = replace('/blogs/1/2/all-blogs/','');
The values 1, 2 and all-blogs can change. Is it possible to make them wildcards?
Thanks in advance,
Regards
You can use .* as a placeholder for "zero or more of any character here" or .+ for "one or more of any character here". I'm not 100% sure exactly what you're trying to do, but for instance:
var str = "/blogs/1/2/all-blogs/";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "", the string is now blank
But if there's more after or before it:
str = "foo/blogs/1/2/all-blogs/bar";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "foobar"
Live example
Note that in both of the above, only the first match will be replaced. If you wanted to replace all matches, add a g like this:
str = str.replace(/\/blogs\/.+\/.+\/.+\//g, '');
// ^-- here
You can read up on JavaScript's regular expressions on MDC.
js> 'www.google.de/blogs/1/2/all-blogs'.replace(/\/blogs\/[^\/]+\/[^\/]+\/[^\/]+\/?/, '');
www.google.de
What about just splitting the string at slashes and just replacing the values?
var myURL = '/blogs/1/2/all-blogs/', fragments, newURL;
fragments = myURL.split('/');
fragments[1] = 3;
fragments[2] = 8;
fragments[3] = 'some-specific-blog';
newURL = fragments.join('/');
That should return:
'/blogs/3/8/some-specific-blog'
Try this
(/.+){4}
escape as appropriate

In Javascript, how can I perform a global replace on string with a variable inside '/' and '/g'?

I want to perform a global replace of string using String.replace in Javascript.
In the documentation I read that I can do this with /g, i.e. for example;
var mystring = mystring.replace(/test/g, mystring);
and this will replace all occurrences inside mystring. No quotes for the expression.
But if I have a variable to find, how can I do this without quotes?
I've tried something like this:
var stringToFind = "test";
//first try
mystring = mystring.replace('/' + stringToFind + '/g', mystring);
//second try, not much sense at all
mystring = mystring.replace(/stringToFind/g, mystring);
but they don't work. Any ideas?
var mystring = "hello world test world";
var find = "world";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "yay")); // alerts "hello yay test yay"
In case you need this into a function
replaceGlobally(original, searchTxt, replaceTxt) {
const regex = new RegExp(searchTxt, 'g');
return original.replace(regex, replaceTxt) ;
}
For regex, new RegExp(stringtofind, 'g');. BUT. If ‘find’ contains characters that are special in regex, they will have their regexy meaning. So if you tried to replace the '.' in 'abc.def' with 'x', you'd get 'xxxxxxx' — whoops.
If all you want is a simple string replacement, there is no need for regular expressions! Here is the plain string replace idiom:
mystring= mystring.split(stringtofind).join(replacementstring);
Regular expressions are much slower then string search. So, creating regex with escaped search string is not an optimal way. Even looping though the string would be faster, but I suggest using built-in pre-compiled methods.
Here is a fast and clean way of doing fast global string replace:
sMyString.split(sSearch).join(sReplace);
And that's it.
String.prototype.replaceAll = function (replaceThis, withThis) {
var re = new RegExp(RegExp.quote(replaceThis),"g");
return this.replace(re, withThis);
};
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
};
var aa = "qwerr.erer".replaceAll(".","A");
alert(aa);
silmiar post
You can use the following solution to perform a global replace on a string with a variable inside '/' and '/g':
myString.replace(new RegExp(strFind, 'g'), strReplace);
Thats a regular expression, not a string. Use the constructor for a RegExp object to dynamically create a regex.
var r = new RegExp(stringToFind, 'g');
mystring.replace(r, 'some replacement text');
Try:
var stringToFind = "test";
mystring = mystring.replace(new RegExp(stringToFind, "g"), mystring);
You can do using following method
see this function:
function SetValue()
{
var txt1='This is a blacK table with BLack pen with bLack lady';
alert(txt1);
var txt2= txt1.replace(/black/gi,'green');
alert(txt2);
}
syntax:
/search_string/{g|gi}
where
g is global case-sensitive replacement
gi is blobal case-insensitive replacement
You can check this JSBIN link
http://jsbin.com/nohuroboxa/edit?html,js,output
If you want variables interpolated, you need to use the RegExp object
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions
Example:
var str = "This is my name";
var replace = "i";
var re = new RegExp(replace, 'g')
str = str.replace(re, 'p');
alert(str);
Dynamic global replace
I came to this thread looking for a slightly more complex solution which isn't answered here. I've now found the answer so I'm going to post it in case anyone else finds it useful.
I wanted to do a dynamic global replace, where the replacement strings are based on the original matches.
For example, to capitalise the first letter of all words (e.g. "cat sat mat" into "Cat Sat Mat") with a global find replace. Here's how to do that.
function capitaliseWords(aString) {
// Global match for lowercase letters following a word boundary
var letters = aString.match(/\b[a-z]/g), i, letterMatch;
// Loop over all matched letters
for( i = 0; i < letters.length; i++ ) {
// Replace the matched letters with upper case versions
letterMatch = new RegExp('\\b'+letters[i]); // EDIT - slight fix
aString = aString.replace(letterMatch, letters[i].toUpperCase());
}
// Return our newly capitalised string
return aString;
}
alert( capitaliseWords("cat sat mat") ); // Alerts "Cat Sat Mat"
WIth modern day linters, they prefer you to regEx literal, so rather than new RegExp it would just be `//
With an example:
'test'.replace(/ /gi, '_')
with the test you are looking to replace inside the regex or the /searchableText/ and then replace text in the second parameter. In my case I wanted to replace all spaces with underscores.
Can you use prototype.js? If so you could use String.gsub, like
var myStr = "a day in a life of a thing";
var replace = "a";
var resultString = myStr.gsub(replace, "g");
// resultString will be "g day in g life of g thing"
It will also take regular expressions. To me this is one of the more elegant ways to solve it. prototypejs gsub documentation

Categories