替换字符串形式的getUrlParameter函数

时间:2018-05-24 10:01:51

标签: javascript string variables url replace

我对getUrlParameter有疑问。我正在检索网址的品牌和型号名称(例如http://www.example.com/?model=SM-9675&brand=Samsung)。 但我想改变这样的品牌名称;如果品牌名称为“三星”,请将三星替换为“Microsoft'”。我怎么能这样做?

Javascript代码:

<script>
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

var brand = getUrlParameter('brand'); //Place brand in var
var model = getUrlParameter('model'); //Place model in var

document.getElementById('brandmodel').innerHTML = brand + " " + model; //place brand and model in HTML.
</script>

HTML:

<span id="brandmodel"></span>

1 个答案:

答案 0 :(得分:0)

只需使用简单的if声明:

if (brand === 'Samsung') {
  brand = 'Microsoft';
}